blob: b2b8f65b904abc450a24cb3b65f95ee6f98c0f2a [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. All Rights Reserved.
2// 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),
115 nonlocals_(0),
116 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()),
126 locals_(),
127 temps_(4),
128 params_(4),
129 nonlocals_(4),
130 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),
142 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
187Variable* Scope::Lookup(Handle<String> name) {
188 return locals_.Lookup(name);
189}
190
191
192Variable* Scope::DeclareFunctionVar(Handle<String> name) {
193 ASSERT(is_function_scope() && function_ == NULL);
194 function_ = new Variable(this, name, Variable::CONST, true, false);
195 return function_;
196}
197
198
199Variable* Scope::Declare(Handle<String> name, Variable::Mode mode) {
200 // DYNAMIC variables are introduces during variable allocation,
201 // INTERNAL variables are allocated explicitly, and TEMPORARY
202 // variables are allocated via NewTemporary().
203 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
204 return locals_.Declare(this, name, mode, true, false);
205}
206
207
208void Scope::AddParameter(Variable* var) {
209 ASSERT(is_function_scope());
210 ASSERT(Lookup(var->name()) == var);
211 params_.Add(var);
212}
213
214
215VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
216 // Note that we must not share the unresolved variables with
217 // the same name because they may be removed selectively via
218 // RemoveUnresolved().
219 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
220 unresolved_.Add(proxy);
221 return proxy;
222}
223
224
225void Scope::RemoveUnresolved(VariableProxy* var) {
226 // Most likely (always?) any variable we want to remove
227 // was just added before, so we search backwards.
228 for (int i = unresolved_.length(); i-- > 0;) {
229 if (unresolved_[i] == var) {
230 unresolved_.Remove(i);
231 return;
232 }
233 }
234}
235
236
237VariableProxy* Scope::NewTemporary(Handle<String> name) {
238 Variable* var = new Variable(this, name, Variable::TEMPORARY, true, false);
239 VariableProxy* tmp = new VariableProxy(name, false, false);
240 tmp->BindTo(var);
241 temps_.Add(var);
242 return tmp;
243}
244
245
246void Scope::AddDeclaration(Declaration* declaration) {
247 decls_.Add(declaration);
248}
249
250
251void Scope::SetIllegalRedeclaration(Expression* expression) {
252 // Only set the illegal redeclaration expression the
253 // first time the function is called.
254 if (!HasIllegalRedeclaration()) {
255 illegal_redecl_ = expression;
256 }
257 ASSERT(HasIllegalRedeclaration());
258}
259
260
261void Scope::VisitIllegalRedeclaration(Visitor* visitor) {
262 ASSERT(HasIllegalRedeclaration());
263 illegal_redecl_->Accept(visitor);
264}
265
266
267template<class Allocator>
268void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
269 // Collect variables in this scope.
270 // Note that the function_ variable - if present - is not
271 // collected here but handled separately in ScopeInfo
272 // which is the current user of this function).
273 for (int i = 0; i < temps_.length(); i++) {
274 Variable* var = temps_[i];
275 if (var->var_uses()->is_used()) {
276 locals->Add(var);
277 }
278 }
279 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
280 Variable* var = reinterpret_cast<Variable*>(p->value);
281 if (var->var_uses()->is_used()) {
282 locals->Add(var);
283 }
284 }
285}
286
287
288// Make sure the method gets instantiated by the template system.
289template void Scope::CollectUsedVariables(
290 List<Variable*, FreeStoreAllocationPolicy>* locals);
291template void Scope::CollectUsedVariables(
292 List<Variable*, PreallocatedStorage>* locals);
293
294
295void Scope::AllocateVariables() {
296 ASSERT(outer_scope_ == NULL); // eval or global scopes only
297
298 // 1) Propagate scope information.
299 // If we are in an eval scope, we may have other outer scopes about
300 // which we don't know anything at this point. Thus we must be conservative
301 // and assume they may invoke eval themselves. Eventually we could capture
302 // this information in the ScopeInfo and then use it here (by traversing
303 // the call chain stack, at compile time).
304 PropagateScopeInfo(is_eval_scope());
305
306 // 2) Resolve variables.
307 Scope* global_scope = NULL;
308 if (is_global_scope()) global_scope = this;
309 ResolveVariablesRecursively(global_scope);
310
311 // 3) Allocate variables.
312 AllocateVariablesRecursively();
313}
314
315
316bool Scope::SupportsEval() const {
317 return scope_calls_eval_ || inner_scope_calls_eval_;
318}
319
320
321bool Scope::AllowsLazyCompilation() const {
322 return !force_eager_compilation_ && HasTrivialOuterContext();
323}
324
325
326bool Scope::HasTrivialContext() const {
327 // A function scope has a trivial context if it always is the global
328 // context. We iteratively scan out the context chain to see if
329 // there is anything that makes this scope non-trivial; otherwise we
330 // return true.
331 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
332 if (scope->is_eval_scope()) return false;
333 if (scope->scope_inside_with_) return false;
334 if (scope->num_heap_slots_ > 0) return false;
335 }
336 return true;
337}
338
339
340bool Scope::HasTrivialOuterContext() const {
341 Scope* outer = outer_scope_;
342 if (outer == NULL) return true;
343 // Note that the outer context may be trivial in general, but the current
344 // scope may be inside a 'with' statement in which case the outer context
345 // for this scope is not trivial.
346 return !scope_inside_with_ && outer->HasTrivialContext();
347}
348
349
350int Scope::ContextChainLength(Scope* scope) {
351 int n = 0;
352 for (Scope* s = this; s != scope; s = s->outer_scope_) {
353 ASSERT(s != NULL); // scope must be in the scope chain
354 if (s->num_heap_slots() > 0) n++;
355 }
356 return n;
357}
358
359
360#ifdef DEBUG
361static const char* Header(Scope::Type type) {
362 switch (type) {
363 case Scope::EVAL_SCOPE: return "eval";
364 case Scope::FUNCTION_SCOPE: return "function";
365 case Scope::GLOBAL_SCOPE: return "global";
366 }
367 UNREACHABLE();
368 return NULL;
369}
370
371
372static void Indent(int n, const char* str) {
373 PrintF("%*s%s", n, "", str);
374}
375
376
377static void PrintName(Handle<String> name) {
378 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
379 PrintF("%s", *s);
380}
381
382
383static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
384 if (var->var_uses()->is_used() || var->rewrite() != NULL) {
385 Indent(indent, Variable::Mode2String(var->mode()));
386 PrintF(" ");
387 PrintName(var->name());
388 PrintF("; // ");
389 if (var->rewrite() != NULL) PrintF("%s, ", printer->Print(var->rewrite()));
390 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access, ");
391 PrintF("var ");
392 var->var_uses()->Print();
393 PrintF(", obj ");
394 var->obj_uses()->Print();
395 PrintF("\n");
396 }
397}
398
399
400void Scope::Print(int n) {
401 int n0 = (n > 0 ? n : 0);
402 int n1 = n0 + 2; // indentation
403
404 // Print header.
405 Indent(n0, Header(type_));
406 if (scope_name_->length() > 0) {
407 PrintF(" ");
408 PrintName(scope_name_);
409 }
410
411 // Print parameters, if any.
412 if (is_function_scope()) {
413 PrintF(" (");
414 for (int i = 0; i < params_.length(); i++) {
415 if (i > 0) PrintF(", ");
416 PrintName(params_[i]->name());
417 }
418 PrintF(")");
419 }
420
421 PrintF(" {\n");
422
423 // Function name, if any (named function literals, only).
424 if (function_ != NULL) {
425 Indent(n1, "// (local) function name: ");
426 PrintName(function_->name());
427 PrintF("\n");
428 }
429
430 // Scope info.
431 if (HasTrivialOuterContext()) {
432 Indent(n1, "// scope has trivial outer context\n");
433 }
434 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
435 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
436 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
437 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
438 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
439 if (num_stack_slots_ > 0) { Indent(n1, "// ");
440 PrintF("%d stack slots\n", num_stack_slots_); }
441 if (num_heap_slots_ > 0) { Indent(n1, "// ");
442 PrintF("%d heap slots\n", num_heap_slots_); }
443
444 // Print locals.
445 PrettyPrinter printer;
446 Indent(n1, "// function var\n");
447 if (function_ != NULL) {
448 PrintVar(&printer, n1, function_);
449 }
450
451 Indent(n1, "// temporary vars\n");
452 for (int i = 0; i < temps_.length(); i++) {
453 PrintVar(&printer, n1, temps_[i]);
454 }
455
456 Indent(n1, "// local vars\n");
457 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
458 Variable* var = reinterpret_cast<Variable*>(p->value);
459 PrintVar(&printer, n1, var);
460 }
461
462 Indent(n1, "// nonlocal vars\n");
463 for (int i = 0; i < nonlocals_.length(); i++)
464 PrintVar(&printer, n1, nonlocals_[i]);
465
466 // Print inner scopes (disable by providing negative n).
467 if (n >= 0) {
468 for (int i = 0; i < inner_scopes_.length(); i++) {
469 PrintF("\n");
470 inner_scopes_[i]->Print(n1);
471 }
472 }
473
474 Indent(n0, "}\n");
475}
476#endif // DEBUG
477
478
479Variable* Scope::NonLocal(Handle<String> name) {
480 // Space optimization: reuse existing non-local with the same name.
481 for (int i = 0; i < nonlocals_.length(); i++) {
482 Variable* var = nonlocals_[i];
483 if (var->name().is_identical_to(name)) {
484 ASSERT(var->mode() == Variable::DYNAMIC);
485 return var;
486 }
487 }
488
489 // Otherwise create a new new-local and add it to the list.
490 Variable* var = new Variable(
491 NULL /* we don't know the scope */,
492 name, Variable::DYNAMIC, true, false);
493 nonlocals_.Add(var);
494
495 // Allocate it by giving it a dynamic lookup.
496 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
497
498 return var;
499}
500
501
502// Lookup a variable starting with this scope. The result is either
503// the statically resolved (local!) variable belonging to an outer scope,
504// or NULL. It may be NULL because a) we couldn't find a variable, or b)
505// because the variable is just a guess (and may be shadowed by another
506// variable that is introduced dynamically via an 'eval' call or a 'with'
507// statement).
508Variable* Scope::LookupRecursive(Handle<String> name, bool inner_lookup) {
509 // If we find a variable, but the current scope calls 'eval', the found
510 // variable may not be the correct one (the 'eval' may introduce a
511 // property with the same name). In that case, remember that the variable
512 // found is just a guess.
513 bool guess = scope_calls_eval_;
514
515 // Try to find the variable in this scope.
516 Variable* var = Lookup(name);
517
518 if (var != NULL) {
519 // We found a variable. If this is not an inner lookup, we are done.
520 // (Even if there is an 'eval' in this scope which introduces the
521 // same variable again, the resulting variable remains the same.
522 // Note that enclosing 'with' statements are handled at the call site.)
523 if (!inner_lookup)
524 return var;
525
526 } else {
527 // We did not find a variable locally. Check against the function variable,
528 // if any. We can do this for all scopes, since the function variable is
529 // only present - if at all - for function scopes.
530 //
531 // This lookup corresponds to a lookup in the "intermediate" scope sitting
532 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
533 // the name of named function literal is kept in an intermediate scope
534 // inbetween this scope and the next outer scope.)
535 if (function_ != NULL && function_->name().is_identical_to(name)) {
536 var = function_;
537
538 } else if (outer_scope_ != NULL) {
539 var = outer_scope_->LookupRecursive(name, true /* inner lookup */);
540 // We may have found a variable in an outer scope. However, if
541 // the current scope is inside a 'with', the actual variable may
542 // be a property introduced via the 'with' statement. Then, the
543 // variable we may have found is just a guess.
544 if (scope_inside_with_)
545 guess = true;
546 }
547
548 // If we did not find a variable, we are done.
549 if (var == NULL)
550 return NULL;
551 }
552
553 ASSERT(var != NULL);
554
555 // If this is a lookup from an inner scope, mark the variable.
556 if (inner_lookup)
557 var->is_accessed_from_inner_scope_ = true;
558
559 // If the variable we have found is just a guess, invalidate the result.
560 if (guess)
561 var = NULL;
562
563 return var;
564}
565
566
567void Scope::ResolveVariable(Scope* global_scope, VariableProxy* proxy) {
568 ASSERT(global_scope == NULL || global_scope->is_global_scope());
569
570 // If the proxy is already resolved there's nothing to do
571 // (functions and consts may be resolved by the parser).
572 if (proxy->var() != NULL) return;
573
574 // Otherwise, try to resolve the variable.
575 Variable* var = LookupRecursive(proxy->name(), false);
576
577 if (proxy->inside_with()) {
578 // If we are inside a local 'with' statement, all bets are off
579 // and we cannot resolve the proxy to a local variable even if
580 // we found an outer matching variable.
581 // Note that we must do a lookup anyway, because if we find one,
582 // we must mark that variable as potentially accessed from this
583 // inner scope (the property may not be in the 'with' object).
584 var = NonLocal(proxy->name());
585
586 } else {
587 // We are not inside a local 'with' statement.
588
589 if (var == NULL) {
590 // We did not find the variable. We have a global variable
591 // if we are in the global scope (we know already that we
592 // are outside a 'with' statement) or if there is no way
593 // that the variable might be introduced dynamically (through
594 // a local or outer eval() call, or an outer 'with' statement),
595 // or we don't know about the outer scope (because we are
596 // in an eval scope).
597 if (!is_global_scope() &&
598 (is_eval_scope() || outer_scope_calls_eval_ ||
599 scope_calls_eval_ || scope_inside_with_)) {
600 // We must look up the variable at runtime, and we don't
601 // know anything else.
602 var = NonLocal(proxy->name());
603
604 } else {
605 // We must have a global variable.
606 ASSERT(global_scope != NULL);
607 var = new Variable(global_scope, proxy->name(),
608 Variable::DYNAMIC, true, false);
609 // Ideally we simply rewrite these variables into property
610 // accesses. Unfortunately, we cannot do this here at the
611 // moment because then we can't differentiate between
612 // global variable ('x') and global property ('this.x') access.
613 // If 'x' doesn't exist, the former leads to an error, while the
614 // latter returns undefined. Sigh...
615 // var->rewrite_ = new Property(new Literal(env_->global()),
616 // new Literal(proxy->name()));
617 }
618 }
619 }
620
621 proxy->BindTo(var);
622}
623
624
625void Scope::ResolveVariablesRecursively(Scope* global_scope) {
626 ASSERT(global_scope == NULL || global_scope->is_global_scope());
627
628 // Resolve unresolved variables for this scope.
629 for (int i = 0; i < unresolved_.length(); i++) {
630 ResolveVariable(global_scope, unresolved_[i]);
631 }
632
633 // Resolve unresolved variables for inner scopes.
634 for (int i = 0; i < inner_scopes_.length(); i++) {
635 inner_scopes_[i]->ResolveVariablesRecursively(global_scope);
636 }
637}
638
639
640bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval) {
641 if (outer_scope_calls_eval) {
642 outer_scope_calls_eval_ = true;
643 }
644
645 bool b = scope_calls_eval_ || outer_scope_calls_eval_;
646 for (int i = 0; i < inner_scopes_.length(); i++) {
647 Scope* inner_scope = inner_scopes_[i];
648 if (inner_scope->PropagateScopeInfo(b)) {
649 inner_scope_calls_eval_ = true;
650 }
651 if (inner_scope->force_eager_compilation_) {
652 force_eager_compilation_ = true;
653 }
654 }
655
656 return scope_calls_eval_ || inner_scope_calls_eval_;
657}
658
659
660bool Scope::MustAllocate(Variable* var) {
661 // Give var a read/write use if there is a chance it might be
662 // accessed via an eval() call, or if it is a global variable.
663 // This is only possible if the variable has a visible name.
664 if ((var->is_this() || var->name()->length() > 0) &&
665 (var->is_accessed_from_inner_scope_ ||
666 scope_calls_eval_ || inner_scope_calls_eval_ ||
667 scope_contains_with_ || var->is_global())) {
668 var->var_uses()->RecordAccess(1);
669 }
670 return var->var_uses()->is_used();
671}
672
673
674bool Scope::MustAllocateInContext(Variable* var) {
675 // If var is accessed from an inner scope, or if there is a
676 // possibility that it might be accessed from the current or
677 // an inner scope (through an eval() call), it must be allocated
678 // in the context.
679 // Exceptions: Global variables and temporary variables must
680 // never be allocated in the (FixedArray part of the) context.
681 return
682 var->mode() != Variable::TEMPORARY &&
683 (var->is_accessed_from_inner_scope_ ||
684 scope_calls_eval_ || inner_scope_calls_eval_ ||
685 scope_contains_with_ || var->is_global());
686}
687
688
689bool Scope::HasArgumentsParameter() {
690 for (int i = 0; i < params_.length(); i++) {
691 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
692 return true;
693 }
694 return false;
695}
696
697
698void Scope::AllocateStackSlot(Variable* var) {
699 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
700}
701
702
703void Scope::AllocateHeapSlot(Variable* var) {
704 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
705}
706
707
708void Scope::AllocateParameterLocals() {
709 ASSERT(is_function_scope());
710 Variable* arguments = Lookup(Factory::arguments_symbol());
711 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
712 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
713 // 'arguments' is used. Unless there is also a parameter called
714 // 'arguments', we must be conservative and access all parameters via
715 // the arguments object: The i'th parameter is rewritten into
716 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
717 // (new) value is always assigned to it via the function
718 // invocation. Then 'arguments' denotes that specific parameter value
719 // and cannot be used to access the parameters, which is why we don't
720 // need to rewrite in that case.
721 //
722 // (*) Instead of having a parameter called 'arguments', we may have an
723 // assignment to 'arguments' in the function body, at some arbitrary
724 // point in time (possibly through an 'eval()' call!). After that
725 // assignment any re-write of parameters would be invalid (was bug
726 // 881452). Thus, we introduce a shadow '.arguments'
727 // variable which also points to the arguments object. For rewrites we
728 // use '.arguments' which remains valid even if we assign to
729 // 'arguments'. To summarize: If we need to rewrite, we allocate an
730 // 'arguments' object dynamically upon function invocation. The compiler
731 // introduces 2 local variables 'arguments' and '.arguments', both of
732 // which originally point to the arguments object that was
733 // allocated. All parameters are rewritten into property accesses via
734 // the '.arguments' variable. Thus, any changes to properties of
735 // 'arguments' are reflected in the variables and vice versa. If the
736 // 'arguments' variable is changed, '.arguments' still points to the
737 // correct arguments object and the rewrites still work.
738
739 // We are using 'arguments'. Tell the code generator that is needs to
740 // allocate the arguments object by setting 'arguments_'.
741 arguments_ = new VariableProxy(Factory::arguments_symbol(), false, false);
742 arguments_->BindTo(arguments);
743
744 // We also need the '.arguments' shadow variable. Declare it and create
745 // and bind the corresponding proxy. It's ok to declare it only now
746 // because it's a local variable that is allocated after the parameters
747 // have been allocated.
748 //
749 // Note: This is "almost" at temporary variable but we cannot use
750 // NewTemporary() because the mode needs to be INTERNAL since this
751 // variable may be allocated in the heap-allocated context (temporaries
752 // are never allocated in the context).
753 Variable* arguments_shadow =
754 new Variable(this, Factory::arguments_shadow_symbol(),
755 Variable::INTERNAL, true, false);
756 arguments_shadow_ =
757 new VariableProxy(Factory::arguments_shadow_symbol(), false, false);
758 arguments_shadow_->BindTo(arguments_shadow);
759 temps_.Add(arguments_shadow);
760
761 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
762 for (int i = 0; i < params_.length(); i++) {
763 Variable* var = params_[i];
764 ASSERT(var->scope() == this);
765 if (MustAllocate(var)) {
766 if (MustAllocateInContext(var)) {
767 // It is ok to set this only now, because arguments is a local
768 // variable that is allocated after the parameters have been
769 // allocated.
770 arguments_shadow->is_accessed_from_inner_scope_ = true;
771 }
772 var->rewrite_ =
773 new Property(arguments_shadow_,
774 new Literal(Handle<Object>(Smi::FromInt(i))),
775 kNoPosition);
776 arguments_shadow->var_uses()->RecordUses(var->var_uses());
777 }
778 }
779
780 } else {
781 // The arguments object is not used, so we can access parameters directly.
782 // The same parameter may occur multiple times in the parameters_ list.
783 // If it does, and if it is not copied into the context object, it must
784 // receive the highest parameter index for that parameter; thus iteration
785 // order is relevant!
786 for (int i = 0; i < params_.length(); i++) {
787 Variable* var = params_[i];
788 ASSERT(var->scope() == this);
789 if (MustAllocate(var)) {
790 if (MustAllocateInContext(var)) {
791 ASSERT(var->rewrite_ == NULL ||
792 (var->slot() != NULL && var->slot()->type() == Slot::CONTEXT));
793 if (var->rewrite_ == NULL) {
794 // Only set the heap allocation if the parameter has not
795 // been allocated yet.
796 AllocateHeapSlot(var);
797 }
798 } else {
799 ASSERT(var->rewrite_ == NULL ||
800 (var->slot() != NULL &&
801 var->slot()->type() == Slot::PARAMETER));
802 // Set the parameter index always, even if the parameter
803 // was seen before! (We need to access the actual parameter
804 // supplied for the last occurrence of a multiply declared
805 // parameter.)
806 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
807 }
808 }
809 }
810 }
811}
812
813
814void Scope::AllocateNonParameterLocal(Variable* var) {
815 ASSERT(var->scope() == this);
816 ASSERT(var->rewrite_ == NULL ||
817 (!var->IsVariable(Factory::result_symbol())) ||
818 (var->slot() == NULL || var->slot()->type() != Slot::LOCAL));
819 if (MustAllocate(var) && var->rewrite_ == NULL) {
820 if (MustAllocateInContext(var)) {
821 AllocateHeapSlot(var);
822 } else {
823 AllocateStackSlot(var);
824 }
825 }
826}
827
828
829DECLARE_bool(usage_computation);
830
831void Scope::AllocateNonParameterLocals() {
832 // Each variable occurs exactly once in the locals_ list; all
833 // variables that have no rewrite yet are non-parameter locals.
834
835 // Sort them according to use such that the locals with more uses
836 // get allocated first.
837 if (FLAG_usage_computation) {
838 // This is currently not implemented.
839 }
840
841 for (int i = 0; i < temps_.length(); i++) {
842 AllocateNonParameterLocal(temps_[i]);
843 }
844
845 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
846 Variable* var = reinterpret_cast<Variable*>(p->value);
847 AllocateNonParameterLocal(var);
848 }
849
850 // Note: For now, function_ must be allocated at the very end. If
851 // it gets allocated in the context, it must be the last slot in the
852 // context, because of the current ScopeInfo implementation (see
853 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
854 if (function_ != NULL) {
855 AllocateNonParameterLocal(function_);
856 }
857}
858
859
860void Scope::AllocateVariablesRecursively() {
861 // The number of slots required for variables.
862 num_stack_slots_ = 0;
863 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
864
865 // Allocate variables for inner scopes.
866 for (int i = 0; i < inner_scopes_.length(); i++) {
867 inner_scopes_[i]->AllocateVariablesRecursively();
868 }
869
870 // Allocate variables for this scope.
871 // Parameters must be allocated first, if any.
872 if (is_function_scope()) AllocateParameterLocals();
873 AllocateNonParameterLocals();
874
875 // Allocate context if necessary.
876 bool must_have_local_context = false;
877 if (scope_calls_eval_ || scope_contains_with_) {
878 // The context for the eval() call or 'with' statement in this scope.
879 // Unless we are in the global or an eval scope, we need a local
880 // context even if we didn't statically allocate any locals in it,
881 // and the compiler will access the context variable. If we are
882 // not in an inner scope, the scope is provided from the outside.
883 must_have_local_context = is_function_scope();
884 }
885
886 // If we didn't allocate any locals in the local context, then we only
887 // need the minimal number of slots if we must have a local context.
888 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
889 !must_have_local_context) {
890 num_heap_slots_ = 0;
891 }
892
893 // Allocation done.
894 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
895}
896
897} } // namespace v8::internal