src/BytecodeCompiler.cpp
author David Anderson <dvander@alliedmods.net>
Sun Sep 16 23:33:48 2012 -0700 (2012-09-16)
changeset 193 970abfc9f077
parent 192 23a804fa1d3e
child 194 b029d63565a2
permissions -rw-r--r--
Fix bug where assigning string literals to references would not create copies.
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of JITCraft.
     6  *
     7  * JITCraft is free software: you can redistribute it and/or modify it under
     8  * the terms of the GNU General Public License as published by the Free
     9  * Software Foundation, either version 3 of the License, or (at your option)
    10  * any later version.
    11  * 
    12  * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
    13  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    15  *
    16  * You should have received a copy of the GNU General Public License along with
    17  * JITCraft. If not, see http://www.gnu.org/licenses/.
    18  */
    19 #include <string.h>
    20 #include "BytecodeCompiler.h"
    21 #include "Scopes.h"
    22 #include "Modules.h"
    23 #include "Types.h"
    24 #include "Array.h"
    25 #include "Strings.h"
    26 #include "Zone.h"
    27 #include "Environments.h"
    28 #include "Box.h"
    29 #include "Heap-inl.h"
    30 
    31 using namespace ke;
    32 
    33 typedef BytecodeEmitter::Label Label;
    34 
    35 #define __ emitter_.
    36 
    37 BytecodeCompiler::BytecodeCompiler(Zone *zone, ParseTree *tree, ModuleData *module)
    38   : zone_(zone),
    39     tree_(tree),
    40     emitter_(zone->pool()),
    41     locals_(NULL),
    42     scope_(NULL),
    43     moduleData_(module),
    44     loop_(NULL)
    45 {
    46 }
    47 
    48 static inline TokenKind
    49 ToCompare(Expression *expr)
    50 {
    51     if (expr->isBinaryExpression()) {
    52         BinaryExpression *b = expr->toBinaryExpression();
    53         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
    54             return b->token();
    55     } else if (expr->isUnaryExpression()) {
    56         UnaryExpression *u = expr->toUnaryExpression();
    57         if (u->token() == TOK_NOT)
    58             return TOK_NOT;
    59     }
    60     return TOK_EOF;
    61 }
    62 
    63 static inline Opcode
    64 CompareTokenToJump(TokenKind kind)
    65 {
    66     switch (kind) {
    67       case TOK_EQUALS:
    68         return OP_JEQ;
    69       case TOK_NOTEQUALS:
    70         return OP_JNE;
    71       case TOK_GT:
    72         return OP_JG;
    73       case TOK_GE:
    74         return OP_JGE;
    75       case TOK_LT:
    76         return OP_JL;
    77       default:
    78         assert(kind == TOK_LE);
    79         return OP_JLE;
    80     }
    81 }
    82 
    83 static inline Opcode
    84 TokenToOpcode(TokenKind kind)
    85 {
    86     switch (kind) {
    87       case TOK_PLUS:
    88         return OP_ADD;
    89       case TOK_MINUS:
    90         return OP_SUB;
    91       case TOK_STAR:
    92         return OP_MUL;
    93       case TOK_SLASH:
    94         return OP_DIV;
    95       case TOK_PERCENT:
    96         return OP_MOD;
    97       case TOK_SHR:
    98         return OP_SHR;
    99       case TOK_USHR:
   100         return OP_USHR;
   101       case TOK_SHL:
   102         return OP_SHL;
   103       case TOK_BITAND:
   104         return OP_BITAND;
   105       case TOK_BITOR:
   106         return OP_BITOR;
   107       case TOK_GT:
   108           return OP_GT;
   109       case TOK_GE:
   110           return OP_GE;
   111       case TOK_LT:
   112           return OP_LT;
   113       case TOK_LE:
   114           return OP_LE;
   115       case TOK_EQUALS:
   116           return OP_EQ;
   117       case TOK_NOTEQUALS:
   118           return OP_NE;
   119       default:
   120         assert(kind == TOK_BITXOR);
   121         return OP_BITXOR;
   122     }
   123 }
   124 
   125 void
   126 BytecodeCompiler::recordLifoSlot(Scope *scope)
   127 {
   128     if (!scope)
   129         return;
   130 
   131     if (Variable *var = scope->lifoSlot()) {
   132         locals_->set(zone_, var->slot(), var->type());
   133         __ savelifo(var->slot());
   134     }
   135 }
   136 
   137 void
   138 BytecodeCompiler::unwindTo(Scope *scope)
   139 {
   140     // Note: we only need to unwind to the outermost scope's LIFO slot.
   141     Variable *var = NULL;
   142     for (Scope *current = scope_; current != scope; current = current->enclosing()) {
   143         if (Variable *slot = current->lifoSlot())
   144             var = slot;
   145     }
   146 
   147     if (var)
   148         __ unwindlifo(var->slot());
   149 }
   150 
   151 void
   152 BytecodeCompiler::visit(NameProxy *name)
   153 {
   154     switch (name->binding()->kind()) {
   155       case BoundName::VARIABLE:
   156       {
   157         Variable *var = name->binding()->toVariable();
   158 
   159         if (var->location() == Variable::STACK) {
   160             __ getlocal(var);
   161             assert(!name->type()->isReference());
   162         } else if (var->location() == Variable::ENVIRONMENT) {
   163             getEnvSlot(var);
   164         } else {
   165             assert(var->location() == Variable::PARAMETER);
   166             __ getarg(var);
   167 
   168             // If this argument is actually a reference, dereference it now.
   169             if (var->type()->isReference())
   170                 __ getref(var->type()->contained());
   171         }
   172         break;
   173       }
   174 
   175       case BoundName::FUNCTION:
   176       {
   177         NamedFunction *fun = name->binding()->toNamedFunction();
   178         __ module();
   179         __ getmodule_fn(fun->slot());
   180         break;
   181       }
   182 
   183       default:
   184       {
   185         NamedConstant *constant = name->binding()->toNamedConstant();
   186         __ int_(constant->value().toInt());
   187         break;
   188       }
   189     }
   190 }
   191 
   192 void
   193 BytecodeCompiler::visit(ExpressionStatement *node)
   194 {
   195     // Expressions leave their value on the top of the stack, so we make sure
   196     // to balance the stack if they're used as a statement.
   197     node->expression()->accept(this);
   198     if (!node->expression()->type()->isVoid())
   199         __ pop();
   200 }
   201 
   202 static inline bool
   203 IsCompositeValueType(Type *type)
   204 {
   205     return type->isStruct() ||
   206            (type->isArray() && type->isFixedLength());
   207 }
   208 
   209 static inline Array *
   210 StringLiteralToArray(Zone *zone, StringLiteral *node)
   211 {
   212     Local<Type> type(zone, node->type());
   213     Local<ArrayMap> map(zone, ArrayMap::Attach(zone, type));
   214     if (!map)
   215         return NULL;
   216 
   217     return Array::NewString(zone,
   218                             map,
   219                             node->string()->raw(),
   220                             node->string()->length(),
   221                             Heap::Tenure_Old);
   222 }
   223 
   224 void
   225 BytecodeCompiler::visit(Assignment *node)
   226 {
   227     Local<Type> left(zone_, node->type());
   228     Local<Type> right(zone_, node->expression()->type());
   229 
   230     // The first step is three sub-steps:
   231     //
   232     //   (1) Bind the left-hand side.
   233     //   -- If a cumulative operation (+=, etc):
   234     //   (2) Save a copy of the binding on the stack.
   235     //   (3) Dereference the binding to get a value.
   236     //
   237     if (node->lvalue()->isNameProxy()) {
   238         NameProxy *proxy = node->lvalue()->toNameProxy();
   239         Variable *var = proxy->binding()->toVariable();
   240 
   241         // We need to fetch the variable under the following circumstances:
   242         //  (1) The variable is a reference, since we'll store into the ref.
   243         //  (2) The variable is a fixed array, since we need to copy into it.
   244         //  (3) The variable is a struct, since we need to copy into it.
   245         if (var->type()->isReference() || IsCompositeValueType(var->type()))
   246             __ get(var);
   247 
   248         // Get the value if needed.
   249         if (node->token() != TOK_ASSIGN) {
   250             // += etc is not allowed on arrays.
   251             assert(!var->type()->isArray());
   252 
   253             if (var->location() == Variable::ENVIRONMENT)
   254                 getEnvSlot(var);
   255 
   256             if (var->type()->isReference()) {
   257                 __ dup();
   258                 __ getref(var->type()->contained());
   259             } else if (var->location() != Variable::ENVIRONMENT) {
   260                 __ get(var);
   261             }
   262         }
   263     } else if (node->lvalue()->isFieldExpression()) {
   264         FieldExpression *expr = node->lvalue()->toFieldExpression();
   265         __ note_position(expr->pos());
   266 
   267         expr->left()->accept(this);
   268 
   269         if (node->token() != TOK_ASSIGN)
   270             __ dup();
   271 
   272         if (node->token() != TOK_ASSIGN || IsCompositeValueType(left))
   273             __ getfield(expr->fieldIndex(), left);
   274     } else {
   275         IndexExpression *index = node->lvalue()->toIndexExpression();
   276         __ note_position(index->pos());
   277 
   278         index->left()->accept(this);
   279         index->right()->accept(this);
   280 
   281         if (node->token() != TOK_ASSIGN)
   282             __ dup2();
   283 
   284         if (node->token() != TOK_ASSIGN || IsCompositeValueType(left))
   285             __ getelem(left);
   286     }
   287 
   288     if (node->token() == TOK_ASSIGN) {
   289         // Special case: if the left-hand side is a string literal, we must
   290         // spawn a new copy (:TODO: something about const?)
   291         if (node->expression()->isStringLiteral() && !left->isFixedLength()) {
   292             Local<Array> string(zone_,
   293                     StringLiteralToArray(zone_, node->expression()->toStringLiteral()));
   294             if (!string)
   295                 return;
   296 
   297             Local<ArrayMap> arrayMap(zone_, ArrayMap::cast(string->map()));
   298             __ note_position(node->expression()->pos());
   299             __ int_(string->length());
   300             __ newarray(OP_NEWSIZED, arrayMap, Heap::Tenure_Default);
   301             __ object(string);
   302             __ copyarray();
   303         } else {
   304             node->expression()->accept(this);
   305         }
   306     } else {
   307         visitForALU(left, node->expression());
   308 
   309         TokenKind alu = TokenKind(int(node->token()) - (TOK_ASSIGN_ADD - TOK_PLUS));
   310         __ note_position(node->pos());
   311         __ binary(TokenToOpcode(alu));
   312     }
   313 
   314     // Emit the store.
   315     if (left->isArray() && left->isFixedLength()) {
   316         // (x = y) returns the left-hand side; if |x| is a fixed-length array,
   317         // then |y| is as well, and we perform a deep copy.
   318         assert(right->isFixedLength());
   319         __ note_position(node->pos());
   320         __ copyarray();
   321     } else if (left->isStruct()) {
   322         // Structs have value semantics, so emit a full copy. We don't break
   323         // this down into u-ops, to avoid unnecessary bytecode explosion.
   324         assert(right->isStruct());
   325         __ note_position(node->pos());
   326         __ copystruct();
   327     } else if (node->lvalue()->isNameProxy()) {
   328         NameProxy *proxy = node->lvalue()->toNameProxy();
   329         Variable *var = proxy->binding()->toVariable();
   330 
   331         if (var->type()->isReference())
   332             __ setref(var->type()->contained());
   333         else if (var->location() == Variable::ENVIRONMENT)
   334             setEnvSlot(var);
   335         else
   336             __ set(var);
   337     } else if (node->lvalue()->isFieldExpression()) {
   338         FieldExpression *expr = node->lvalue()->toFieldExpression();
   339         __ setfield(expr->fieldIndex(), left);
   340     } else {
   341         __ setelem(left);
   342     }
   343 }
   344 
   345 void
   346 BytecodeCompiler::visit(IncDecExpression *node)
   347 {
   348     // In the postfix case, the logic looks like:
   349     //      (1) Bind       -> REF
   350     //      (2) Dup        -> REF REF
   351     //      (3) Fetch      -> REF VAL
   352     //      (4) Swap       -> VAL REF
   353     //      (5) Pick       -> VAL REF VAL
   354     //      (6) Add        -> VAL REF VAL+1
   355     //      (7) Store      -> VAL VAL+1
   356     //      (8) Drop       -> VAL
   357     //
   358     // In the prefix case, the logic looks like:
   359     //      (1) Bind       -> REF
   360     //      (2) Dup        -> REF REF
   361     //      (3) Fetch      -> REF VAL
   362     //      --
   363     //      --
   364     //      (6) Add        -> REF VAL+1
   365     //      (7) Store      -> VAL+1
   366     //      --
   367     //
   368     // This is squirrely enough such that we don't bother sharing too much
   369     // with the above.
   370     // 
   371     // Note: We simulate a "Pick" operation with a dup2+pop.
   372 
   373     // This is steps (1) to (5).
   374     Expression *expr = node->expression();
   375     if (expr->isNameProxy()) {
   376         NameProxy *proxy = expr->toNameProxy();
   377         Variable *var = proxy->binding()->toVariable();
   378 
   379         // Bind.
   380         if (var->location() == Variable::ENVIRONMENT)
   381             getEnvSlot(var);
   382         else if (var->type()->isReference() || var->type()->isArray())
   383             __ get(var);
   384 
   385         // Dup and fetch.
   386         if (var->type()->isReference()) {
   387             __ dup();
   388             __ getref(node->type());
   389             if (node->postfix()) {
   390                 __ swap();
   391                 __ pick2();
   392             }
   393         } else {
   394             assert(!var->type()->isArray());
   395             if (var->location() != Variable::ENVIRONMENT)
   396                 __ get(var);
   397             if (node->postfix())
   398                 __ dup();
   399         }
   400     } else if (expr->isFieldExpression()) {
   401         FieldExpression *field = expr->toFieldExpression();
   402 
   403         field->left()->accept(this);
   404         __ dup();
   405         __ getfield(field->fieldIndex(), field->type());
   406 
   407         if (node->postfix()) {
   408             // The stack looks like this now:
   409             // OBJECT VALUE
   410             __ swap();          // VALUE OBJECT
   411             __ pick2();         // VALUE OBJECT VALUE
   412         }
   413     } else {
   414         IndexExpression *index = expr->toIndexExpression();
   415         __ note_position(index->pos());
   416 
   417         index->left()->accept(this);
   418         index->right()->accept(this);
   419 
   420         assert(!node->type()->isArray());
   421         __ dup2();
   422         __ getelem(node->type());
   423 
   424         if (node->postfix()) {
   425             // The stack looks like this now:
   426             // ARRAY INDEX VALUE
   427             //
   428             // So we must use a PICK operation to rotate the stack into position.
   429             __ roll3();         // INDEX VALUE ARRAY
   430             __ roll3();         // VALUE ARRAY INDEX
   431             __ pick3();         // VALUE ARRAY INDEX VALUE
   432         }
   433     }
   434 
   435     // Perform step (6).
   436     if (node->type()->isFloat()) {
   437         __ float_(1.0);
   438     } else {
   439         assert(node->type()->isInt32());
   440         __ int_(1);
   441     }
   442 
   443     __ note_position(node->pos());
   444     if (node->token() == TOK_INCREMENT)
   445         __ binary(OP_ADD);
   446     else
   447         __ binary(OP_SUB);
   448 
   449     // Perform step (7).
   450     if (expr->isNameProxy()) {
   451         NameProxy *proxy = expr->toNameProxy();
   452         Variable *var = proxy->binding()->toVariable();
   453 
   454         if (var->type()->isReference())
   455             __ setref(node->type());
   456         else if (var->location() == Variable::ENVIRONMENT)
   457             setEnvSlot(var);
   458         else
   459             __ set(var);
   460     } else if (expr->isFieldExpression()) {
   461         FieldExpression *field = expr->toFieldExpression();
   462         __ setfield(field->fieldIndex(), field->type());
   463     } else {
   464         assert(expr->isIndexExpression());
   465         __ setelem(node->type());
   466     }
   467 
   468     // Perform step (8).
   469     if (node->postfix())
   470         __ pop();
   471 }
   472 
   473 void
   474 BytecodeCompiler::visitForALU(Type *needed, Expression *node)
   475 {
   476     node->accept(this);
   477     if (needed->isFloat() && !node->type()->isFloat())
   478         __ cvt_i2f();
   479     else
   480         assert(needed->primitive() == node->type()->primitive());
   481 }
   482 
   483 static inline Type *
   484 GetCoercionType(TokenKind tok, Type *left, Type *right)
   485 {
   486     if (left->isFloat())
   487         return left;
   488     return right;
   489 }
   490 
   491 void
   492 BytecodeCompiler::visit(UnaryExpression *node)
   493 {
   494     Local<Type> out(zone_, ((Expression *)node)->type());
   495 
   496     switch (node->token()) {
   497       case TOK_MINUS:
   498       {
   499         Local<Type> type(zone_, node->expression()->type());
   500         node->expression()->accept(this);
   501         
   502         if (out->isFloat())
   503             __ neg_f();
   504         else
   505             __ neg();
   506         break;
   507       }
   508 
   509       case TOK_NOT:
   510       {
   511         Local<Type> type(zone_, node->expression()->type());
   512         node->expression()->accept(this);
   513         
   514         if (out->isFloat())
   515             __ not_f();
   516         else
   517             __ not_();
   518         break;
   519       }
   520 
   521       case TOK_LABEL:
   522       {
   523         Local<Type> from(zone_, node->expression()->type());
   524 
   525         node->expression()->accept(this);
   526         if (!from->isFloat() && out->isFloat())
   527             __ bits_f2i();
   528         else if (from->isFloat() && !out->isFloat())
   529             __ bits_i2f();
   530         break;
   531       }
   532 
   533       default:
   534         assert(node->token() == TOK_TILDE);
   535         node->expression()->accept(this);
   536         __ bitnot();
   537         break;
   538     }
   539 }
   540 
   541 void
   542 BytecodeCompiler::visit(BinaryExpression *node)
   543 {
   544     if (node->token() == TOK_AND || node->token() == TOK_OR) {
   545         Label success, failure, done;
   546         visitForTest(node, &success, &failure, &success);
   547         __ bind(&success);
   548         __ int_(1);
   549         __ drop(1);         // Otherwise, the stack depth will be +1 too much.
   550         __ jump(&done);
   551         __ bind(&failure);
   552         __ int_(0);
   553         __ bind(&done);
   554         return;
   555     }
   556 
   557     Local<Type> leftType(zone_, node->left()->type());
   558     Local<Type> rightType(zone_, node->right()->type());
   559     Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
   560 
   561     visitForALU(coerce, node->left());
   562     visitForALU(coerce, node->right());
   563 
   564     Opcode op = TokenToOpcode(node->token());
   565     if (node->type()->isFloat())
   566         op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
   567 
   568     __ note_position(node->pos());
   569     __ binary(op);
   570 }
   571 
   572 void
   573 BytecodeCompiler::visit(IndexExpression *node)
   574 {
   575     node->left()->accept(this);
   576     node->right()->accept(this);
   577     __ note_position(node->pos());
   578     __ getelem(node->type());
   579 }
   580 
   581 void
   582 BytecodeCompiler::visit(FieldExpression *node)
   583 {
   584     node->left()->accept(this);
   585     __ getfield(node->fieldIndex(), node->type());
   586 }
   587 
   588 void
   589 BytecodeCompiler::visit(ReturnStatement *node)
   590 {
   591     if (node->expression()) {
   592         node->expression()->accept(this);
   593         __ return_();
   594     } else {
   595         __ returnvoid();
   596     }
   597 }
   598 
   599 void
   600 BytecodeCompiler::visitForTest(Expression *expression,
   601                                Label *trueBranch,
   602                                Label *falseBranch,
   603                                Label *fallthrough)
   604 {
   605     TokenKind token = ToCompare(expression);
   606     if (token == TOK_EOF || token == TOK_NOT) {
   607         if (token == TOK_EOF)
   608             expression->accept(this);
   609         else
   610             expression->toUnaryExpression()->expression()->accept(this);
   611         
   612         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   613 
   614         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   615         if (expression->type()->isFloat())
   616             op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   617 
   618         if (fallthrough == falseBranch)
   619             __ j(op, trueBranch);
   620         else
   621             __ j(op, falseBranch); 
   622         return;
   623     }
   624 
   625     BinaryExpression *binary = expression->toBinaryExpression();
   626 
   627     if (token == TOK_AND || token == TOK_OR) {
   628         Label next;
   629         if (token == TOK_AND)
   630             visitForTest(binary->left(), &next, falseBranch, &next);
   631         else
   632             visitForTest(binary->left(), trueBranch, &next, &next);
   633         __ bind(&next);
   634         visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
   635         return;
   636     }
   637 
   638     Opcode op = CompareTokenToJump(token);
   639     if (fallthrough == trueBranch)
   640         op = Invert(op);
   641 
   642     Local<Type> leftType(zone_, binary->left()->type());
   643     Local<Type> rightType(zone_, binary->right()->type());
   644     Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
   645 
   646     visitForALU(coerce, binary->left());
   647     visitForALU(coerce, binary->right());
   648     if (coerce->isFloat())
   649         op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   650 
   651     if (fallthrough == trueBranch)
   652         __ j(op, falseBranch);
   653     else
   654         __ j(op, trueBranch);
   655 }
   656 
   657 void
   658 BytecodeCompiler::visit(ForStatement *node)
   659 {
   660     AutoEnterScope forScope(this, node->scope());
   661 
   662     recordLifoSlot(node->scope());
   663 
   664     Label join, update;
   665     LoopScope loop(scope_, &join, &update, &loop_);
   666 
   667     if (node->initialization())
   668         node->initialization()->accept(this);
   669 
   670     Label header, test;
   671     if (node->condition())
   672         __ jump(&test);
   673 
   674     __ bind(&header);
   675     node->body()->accept(this);
   676 
   677     __ bind(&update);
   678     if (node->update())
   679         node->update()->accept(this);
   680 
   681     if (node->condition()) {
   682         __ bind(&test);
   683         visitForTest(node->condition(), &header, &join, &join);
   684     } else {
   685         __ jump(&header);
   686     }
   687 
   688     __ bind(&join);
   689 
   690     if (node->scope())
   691         unwindTo(node->scope()->enclosing());
   692     assert(__ stackDepth() == 0);
   693 }
   694 
   695 void
   696 BytecodeCompiler::visit(WhileStatement *node)
   697 {
   698     Label header, join;
   699 
   700     __ bind(&header);
   701 
   702     LoopScope loop(scope_, &join, &header, &loop_);
   703 
   704     if (node->token() == TOK_WHILE) {
   705         Label body;
   706 
   707         visitForTest(node->condition(), &body, &join, &body);
   708         __ bind(&body);
   709         node->body()->accept(this);
   710         __ jump(&header);
   711     } else {
   712         node->body()->accept(this);
   713         visitForTest(node->condition(), &header, &join, &join);
   714     }
   715 
   716     __ bind(&join);
   717 }
   718 
   719 void
   720 BytecodeCompiler::visit(BreakStatement *node)
   721 {
   722     unwindTo(loop_->scope());
   723     __ jump(loop_->break_());
   724 }
   725 
   726 void
   727 BytecodeCompiler::visit(ContinueStatement *node)
   728 {
   729     unwindTo(loop_->scope());
   730     __ jump(loop_->continue_());
   731 }
   732 
   733 void
   734 BytecodeCompiler::visit(BlockStatement *node)
   735 {
   736     AutoEnterScope blockScope(this, node->scope());
   737 
   738     recordLifoSlot(node->scope());
   739 
   740     for (size_t i = 0; i < node->statements()->length(); i++) {
   741         Statement *statement = node->statements()->at(i);
   742         statement->accept(this);
   743         assert(__ stackDepth() == 0);
   744     }
   745 
   746     // We don't bother emitting an "unwind" instruction for function scopes,
   747     // since this is taken care of by the calling convention.
   748     if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
   749         unwindTo(node->scope()->enclosing());
   750 }
   751 
   752 void
   753 BytecodeCompiler::visit(IntegerLiteral *node)
   754 {
   755     __ int_(node->value());
   756 }
   757 
   758 void
   759 BytecodeCompiler::visit(BooleanLiteral *node)
   760 {
   761     if (node->token() == TOK_TRUE)
   762         __ true_();
   763     else
   764         __ false_();
   765 }
   766 
   767 void
   768 BytecodeCompiler::visit(FloatLiteral *node)
   769 {
   770     __ float_((float)node->value());
   771 }
   772 
   773 void
   774 BytecodeCompiler::visit(StringLiteral *node)
   775 {
   776     Local<Array> array(zone_, StringLiteralToArray(zone_, node));
   777     if (!array)
   778         return;
   779 
   780     __ note_position(node->pos());
   781     __ object(array);
   782 }
   783 
   784 void
   785 BytecodeCompiler::getEnvSlot(Variable *var)
   786 {
   787     assert(var->scope()->kind() == Scope::GLOBAL);
   788     __ getglobal(var);
   789 }
   790 
   791 void
   792 BytecodeCompiler::setEnvSlot(Variable *var)
   793 {
   794     assert(var->scope()->kind() == Scope::GLOBAL);
   795     __ setglobal(var);
   796 }
   797 
   798 static bool
   799 FillArrayLiteral_String(Zone *zone, Handle<Array> array, ArrayLiteral *literal, unsigned *maxsize)
   800 {
   801     Local<Array> string(zone);
   802     for (size_t i = 0; i < literal->expressions()->length(); i++) {
   803         Expression *expr = literal->expressions()->at(i);
   804         StringLiteral *lit = expr->toStringLiteral();
   805         if ((string = StringLiteralToArray(zone, lit)) == NULL)
   806             return false;
   807 
   808         array->writeObject(zone, i, string);
   809 
   810         if (string->length() > *maxsize)
   811             *maxsize = string->length();
   812 
   813         assert(!array->type()->contained()->isFixedLength() ||
   814                 array->type()->contained()->fixedLength() >= string->length());
   815     }
   816 
   817     return true;
   818 }
   819 
   820 static bool
   821 FillArrayLiteral_Primitive(Zone *zone, Handle<Array> array, ArrayLiteral *literal)
   822 {
   823     assert(array->type()->fixedLength() == literal->expressions()->length());
   824 
   825     for (size_t i = 0; i < literal->expressions()->length(); i++) {
   826         Expression *expr = literal->expressions()->at(i);
   827         if (IntegerLiteral *lit = expr->asIntegerLiteral()) {
   828             array->writeInt32(i, lit->value());
   829             continue;
   830         }
   831         if (BooleanLiteral *lit = expr->asBooleanLiteral()) {
   832             if (lit->token() == TOK_TRUE)
   833                 array->writeInt32(i, 1);
   834             else
   835                 array->writeInt32(i, 0);
   836             continue;
   837         }
   838         if (FloatLiteral *lit = expr->asFloatLiteral()) {
   839             array->writeFloat(i, lit->value());
   840             continue;
   841         }
   842 
   843         // Unrecognized literal type.
   844         assert(false);
   845     }
   846 
   847     return true;
   848 }
   849 
   850 static bool
   851 TraverseArrayLiteral(Zone *zone, ArrayLiteral *literal, Handle<Array> array, Handle<Type> type,
   852                      unsigned *maxsize)
   853 {
   854     assert(type->fixedLength() == literal->expressions()->length());
   855 
   856     Local<Type> contained(zone, type->contained());
   857     if (contained->isCharArray())
   858         return FillArrayLiteral_String(zone, array, literal, maxsize);
   859 
   860     if (!contained->isArray())
   861         return FillArrayLiteral_Primitive(zone, array, literal);
   862 
   863     Local<Array> subarray(zone);
   864     for (size_t i = 0; i < literal->expressions()->length(); i++) {
   865         Expression *expr = literal->expressions()->at(i);
   866         subarray = Array::cast(array->readObject(i));
   867         if (!TraverseArrayLiteral(zone, expr->toArrayLiteral(), subarray, contained, maxsize))
   868             return false;
   869     }
   870 
   871     return true;
   872 }
   873 
   874 static Array *
   875 BuildArrayLiteral(Zone *zone, ArrayLiteral *literal, Handle<ArrayMap> map, unsigned *maxsize)
   876 {
   877     Local<Array> root(zone, Array::NewFixed(zone, map, Heap::Tenure_Old));
   878     if (!root)
   879         return NULL;
   880 
   881     // This should have allocated everything in the array, so all we need to
   882     // do is traverse down to the lowest levels and copy things.
   883     Local<Type> type(zone, map->type());
   884     if (!TraverseArrayLiteral(zone, literal, root, type, maxsize))
   885         return NULL;
   886 
   887     return root;
   888 }
   889 
   890 static inline bool
   891 ArrayContainsCharBuffers(Type *type)
   892 {
   893     if (type->contained()->isArray())
   894         return ArrayContainsCharBuffers(type->contained());
   895     return type->isCharArray();
   896 }
   897 
   898 void
   899 BytecodeCompiler::visit(VariableDeclaration *node)
   900 {
   901     Variable *var = node->variable();
   902     
   903     Local<Type> type(zone_, var->type());
   904     if (type->isArray()) {
   905         Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
   906         __ note_position(node->pos());
   907 
   908         Local<Type> right(zone_);
   909         if (node->initialization())
   910             right = node->initialization()->type();
   911 
   912         // There are a few methods for allocating, here:
   913         // (1) If the array is fixed,
   914         //    (a) Initializer not present,
   915         //              NEWFIXED
   916         //    (b) Left is const non-string:
   917         //              <nothing>
   918         //    (b) Otherwise:
   919         //              NEWFIXED
   920         //              COPYARRAY
   921         // (2) If the array is not fixed,
   922         //    (a) Initializer is not present,
   923         //              NEWEMPTY
   924         //    (b) Initializer is not a string literal,
   925         //        or left is const:
   926         //              <nothing>
   927         //    (c) Initializer is a string literal,
   928         //              NEWSIZED
   929         //              COPYARRAY
   930         //
   931 
   932         Heap::Tenure tenure = var->scope()->kind() == Scope::GLOBAL
   933                               ? Heap::Tenure_Old
   934                               : Heap::Tenure_Default;
   935 
   936         if (Expression *init = node->initialization()) {
   937             if (init->isArrayLiteral()) {
   938                 unsigned maxsize = 0;
   939                 Local<Array> array(zone_, BuildArrayLiteral(zone_, init->toArrayLiteral(), map, &maxsize));
   940                 if (!array)
   941                     return;
   942 
   943                 assert(type->isFixedLength());
   944 
   945                 if (type->isConst()) {
   946                     __ object(array);
   947                 } else if (ArrayContainsCharBuffers(type)) {
   948                     // This array contains mutable char buffers, so
   949                     // unfortunately this gets a little more complicated. We
   950                     // compute the maximum size needed for the innermost
   951                     // string, which is similar to SP1. This means we can use
   952                     // CopyArray rather than individually emit opcodes to clone
   953                     // every string.
   954                     Local<Type> child(zone_, type);
   955                     for (size_t i = 0; i < type->levels() - 1; i++) {
   956                         __ int_(child->fixedLength());
   957                         child = child->contained();
   958                     }
   959                     __ int_(maxsize);
   960                     __ newarray(OP_NEWSIZED, map, tenure);
   961                     __ object(array);
   962                     __ copyarray();
   963                 } else {
   964                     __ newarray(OP_NEWFIXED, map, tenure);
   965                     __ object(array);
   966                     __ copyarray();
   967                 }
   968             } else if (type->isFixedLength()) {
   969                 // Note in the case of:
   970                 // const String:buffer[50] = "hello";
   971                 //
   972                 // We want to preserve sizeof(buffer) == 50.
   973                 if (type->isConst() && !type->isCharArray()) {
   974                     init->accept(this);
   975                 } else {
   976                     __ newarray(OP_NEWFIXED, map, tenure);
   977                     init->accept(this);
   978                     __ copyarray();
   979                 }
   980             } else if (!type->isConst() && init->isStringLiteral()) {
   981                 // This is a degenerate case of ArrayLiteral.
   982                 __ int_(right->fixedLength());
   983                 __ newarray(OP_NEWSIZED, map, tenure);
   984                 init->accept(this);
   985                 __ copyarray();
   986             } else if (type->isConst()) {
   987                 init->accept(this);
   988             }
   989         } else if (type->isFixedLength()) {
   990             __ newarray(OP_NEWFIXED, map, tenure);
   991         } else {
   992             if (node->postDimensions()) {
   993                 for (size_t i = 0; i < node->postDimensions()->length(); i++) {
   994                     Expression *expr = node->postDimensions()->at(i);
   995                     if (expr)
   996                         expr->accept(this);
   997                     else
   998                         __ int_(0);
   999                 }
  1000                 __ newarray(OP_NEWSIZED, map, tenure);
  1001             } else {
  1002                 __ newarray(OP_NEWEMPTY, map, tenure);
  1003             }
  1004         }
  1005     } else if (type->isStruct()) {
  1006         Local<StructMap> map(zone_, StructMap::cast(type->newMap()));
  1007 
  1008         // Because structs can contain arrays, any sort of composition
  1009         // triggers non-LIFO allocation. This is just for correctness.
  1010         // We could do better by:
  1011         //  (1) Limiting to structs that just (recursively) contain arrays,
  1012         //  (2) Swap Stack for Default tenure in Struct::New
  1013         //  (3) JIT analysis
  1014         if (var->scope()->kind() == Scope::GLOBAL)
  1015             __ newstruct(map, Heap::Tenure_Old);
  1016         else if (var->needsHeapAllocation() || map->composed())
  1017             __ newstruct(map, Heap::Tenure_Default);
  1018         else
  1019             __ newstruct(map, Heap::Tenure_Stack);
  1020     } else {
  1021         if (node->initialization()) {
  1022             node->initialization()->accept(this);
  1023         } else {
  1024             if (type->isInt32OrEnum() || type->isBool()) {
  1025                 __ int_(0);
  1026             } else {
  1027                 assert(type->isFloat());
  1028                 __ float_(0);
  1029             }
  1030         }
  1031     }
  1032 
  1033     if (var->location() == Variable::STACK) {
  1034         __ setlocal(var);
  1035         locals_->set(zone_, var->slot(), var->type());
  1036     } else {
  1037         assert(var->location() == Variable::ENVIRONMENT);
  1038         setEnvSlot(var);
  1039     }
  1040 
  1041     __ pop();
  1042 }
  1043 
  1044 void
  1045 BytecodeCompiler::visit(CallExpression *node)
  1046 {
  1047     Local<Type> funType(zone_, node->callee()->type());
  1048 
  1049     // Sniff out natives, which have a specific opcode and are guaranteed to
  1050     // be called via name proxy.
  1051     NamedFunction *native = NULL;
  1052     if (funType->isNative())
  1053         native = node->callee()->toNameProxy()->binding()->toNamedFunction();
  1054 
  1055     Local<Type> given(zone_);
  1056     for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
  1057         Expression *arg = node->arguments()->at(i);
  1058 
  1059         given = arg->type();
  1060 
  1061         // We need to compute a reference if the parameter was in the form:
  1062         //  f(&a)
  1063         // Note this form does not allow: f({})
  1064         // 
  1065         // We also need to compute references for all variadic native
  1066         // arguments, but arrays and references are already in the
  1067         // appropriate form.
  1068         bool mustPushReference = false;
  1069         if (i >= funType->parameters()->length()) {
  1070             assert(funType->isNative() && funType->isNativeVariadic());
  1071             mustPushReference = !given->isArray() && !given->isReference();
  1072         } else if (funType->parameterAt(i)->isReference()) {
  1073             mustPushReference = !given->isReference();
  1074         }
  1075 
  1076         // If a native is passed to a native, it must only be one level deep.
  1077         assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
  1078 
  1079         if (mustPushReference) {
  1080             if (arg->isNameProxy()) {
  1081                 // :TODO: test with functions and globals
  1082                 // Compute a reference to the name.
  1083                 Variable *var = arg->toNameProxy()->binding()->toVariable();
  1084                 __ note_position(node->pos());
  1085                 __ newref(var);
  1086             } else if (arg->isFieldExpression()) {
  1087                 FieldExpression *expr = arg->toFieldExpression();
  1088                 expr->left()->accept(this);
  1089                 __ note_position(expr->pos());
  1090                 __ fieldref_lifo(expr->fieldIndex());
  1091             } else {
  1092                 // We don't know how to, or can't, build a direct reference to
  1093                 // this type. Make an indirect one, by taking the top of the
  1094                 // stack and boxing it up.
  1095                 arg->accept(this);
  1096                 __ note_position(node->pos());
  1097                 __ slotref_lifo();
  1098             }
  1099         } else {
  1100             arg->accept(this);
  1101         }
  1102     }
  1103 
  1104     unsigned argc = node->arguments()->length();
  1105 
  1106     // If there are missing arguments, then we're not done and have to push
  1107     // default parameters.
  1108     Local<Box> box(zone_);
  1109     Local<Array> array(zone_);
  1110     Local<ArrayMap> map(zone_);
  1111     for (size_t i = node->arguments()->length(); i < funType->parameters()->length(); i++) {
  1112         box = Box::cast(funType->defaults()->at(i));
  1113 
  1114         if (box->type()->isPod()) {
  1115             if (box->type()->pod() == PrimitiveType_Int32)
  1116                 __ int_(box->toInt32());
  1117             else if (box->type()->pod() == PrimitiveType_Float)
  1118                 __ float_(box->toFloat());
  1119             else
  1120                 assert(false);
  1121 
  1122             if (funType->parameterAt(i)->isReference()) {
  1123                 __ note_position(node->pos());
  1124                 __ slotref_lifo();
  1125             }
  1126         } else {
  1127             assert(box->type()->isArray());
  1128 
  1129             array = Array::cast(box->toObject());
  1130             if (funType->parameterAt(i)->isConst()) {
  1131                 __ object(array);
  1132             } else {
  1133                 // We need to copy the array since it's mutable. Note that
  1134                 // although COPYARRAY returns its left-hand side, this may
  1135                 // change in the future, we do the same thing and dupe the
  1136                 // newly allocated array.
  1137                 map = ArrayMap::cast(array->map());
  1138                 
  1139                 // Natives cannot escape array references, so we can allocate
  1140                 // them on the LIFO stack.
  1141                 if (funType->isNative())
  1142                     __ newarray(OP_NEWFIXED, map, Heap::Tenure_Stack);
  1143                 else
  1144                     __ newarray(OP_NEWFIXED, map, Heap::Tenure_Default);
  1145                 __ dup();
  1146                 __ object(array);
  1147                 __ copyarray();
  1148                 __ pop();
  1149             }
  1150         }
  1151 
  1152         argc++;
  1153     }
  1154 
  1155     __ note_position(node->pos());
  1156     if (native) {
  1157         __ callnative(native->slot(), argc);
  1158         __ drop(argc);
  1159     } else {
  1160         node->callee()->accept(this);
  1161         __ call(funType);
  1162         __ drop(argc + 1);
  1163     }
  1164 }
  1165 
  1166 void
  1167 BytecodeCompiler::visit(TernaryExpression *node)
  1168 {
  1169     Label success, failure, join;
  1170 
  1171     visitForTest(node->condition(), &success, &failure, &success);
  1172     __ bind(&success);
  1173     node->left()->accept(this);
  1174     __ drop(1);
  1175     __ jump(&join);
  1176     __ bind(&failure);
  1177     node->right()->accept(this);
  1178     __ bind(&join);
  1179 }
  1180 
  1181 void
  1182 BytecodeCompiler::visit(IfStatement *node)
  1183 {
  1184     Label join;
  1185     if (!node->ifFalse()) {
  1186         Label success;
  1187 
  1188         visitForTest(node->condition(), &success, &join, &success);
  1189         __ bind(&success);
  1190         node->ifTrue()->accept(this);
  1191     } else {
  1192         Label success, next;
  1193 
  1194         visitForTest(node->condition(), &success, &next, &success);
  1195         __ bind(&success);
  1196         node->ifTrue()->accept(this);
  1197         __ jump(&join);
  1198         __ bind(&next);
  1199         node->ifFalse()->accept(this);
  1200     }
  1201 
  1202     __ bind(&join);
  1203 }
  1204 
  1205 bool
  1206 BytecodeCompiler::tableswitch(SwitchStatement *node)
  1207 {
  1208     CaseValueList *values = node->caseValueList();
  1209 
  1210     if (values->length() < 3)
  1211         return false;
  1212 
  1213     // Find the delta between the largest and smallest value.
  1214     int hi = values->at(values->length() - 1).box.toInt();
  1215     int lo = values->at(0).box.toInt();
  1216     assert(hi > lo);
  1217 
  1218     unsigned tablesize = TableSwitchEntries(lo, hi);
  1219     if (tablesize > MAX_TABLESWITCH_ENTRIES)
  1220         return false;
  1221 
  1222     Label def, join;
  1223 
  1224     // Create the list of labels that each statement will bind to.
  1225     Label *labels = new Label[node->cases()->length()];
  1226 
  1227     // Create the table of labels we'll use for each case.
  1228     Label **table = new Label *[tablesize];
  1229 
  1230     // Link all cases, by default, to the default label.
  1231     for (size_t i = 0; i < tablesize; i++)
  1232         table[i] = &def;
  1233 
  1234     // Now patch actual cases to their correct labels.
  1235     for (size_t i = 0; i < values->length(); i++) {
  1236         CaseValue &v = values->at(i);
  1237         assert(v.statement < node->cases()->length());
  1238 
  1239         unsigned index = unsigned(v.box.toInt() - lo);
  1240         assert(index < tablesize);
  1241 
  1242         table[index] = &labels[v.statement];
  1243     }
  1244 
  1245     // Emit the tableswitch opcode and the jump table.
  1246     __ tableswitch(lo, hi, &def, table);
  1247 
  1248     // We're done with the jump table now.
  1249     delete [] table;
  1250 
  1251     // Emit each statement.
  1252     for (size_t i = 0; i < node->cases()->length(); i++) {
  1253         Statement *stmt = node->cases()->at(i)->statement();
  1254 
  1255         __ bind(&labels[i]);
  1256         stmt->accept(this);
  1257         __ jump(&join);
  1258     }
  1259 
  1260     // We're done with the statement labels.
  1261     delete [] labels;
  1262 
  1263     // Emit the default case.
  1264     __ bind(&def);
  1265     if (node->defaultCase())
  1266         node->defaultCase()->accept(this);
  1267 
  1268     __ bind(&join);
  1269 
  1270     return true;
  1271 }
  1272 
  1273 void
  1274 BytecodeCompiler::visit(SwitchStatement *node)
  1275 {
  1276     node->expression()->accept(this);
  1277 
  1278     if (tableswitch(node))
  1279         return;
  1280 
  1281     Label join;
  1282 
  1283     for (size_t i = 0; i < node->cases()->length(); i++) {
  1284         Case *c = node->cases()->at(i);
  1285 
  1286         Label success, fail;
  1287         if (c->others()) {
  1288             for (size_t j = 0; j < c->others()->length(); j++) {
  1289                 Expression *expr = c->others()->at(j);
  1290 
  1291                 __ dup();
  1292                 expr->accept(this);
  1293                 __ j(OP_JEQ, &success);
  1294             }
  1295         }
  1296 
  1297         // The final test.
  1298         __ dup();
  1299         c->expression()->accept(this);
  1300         __ j(OP_JNE, &fail);
  1301         __ bind(&success);
  1302         c->statement()->accept(this);
  1303         __ jump(&join);
  1304         __ bind(&fail);
  1305     }
  1306 
  1307     if (node->defaultCase())
  1308         node->defaultCase()->accept(this);
  1309 
  1310     __ pop();
  1311     __ bind(&join);
  1312 }
  1313 
  1314 void
  1315 BytecodeCompiler::visit(FunctionStatement *node)
  1316 {
  1317     if (!node->fun()->used())
  1318         return;
  1319 
  1320     if (node->fun()->isNative()) {
  1321         assert(!moduleData_->natives->at(node->fun()->slot()));
  1322 
  1323         Local<Type> type(zone_, node->fun()->type());
  1324         Local<String> name(zone_, node->fun()->name());
  1325         Local<Native> native(zone_, Native::New(zone_, type, name));
  1326         if (!native)
  1327             return;
  1328 
  1329         moduleData_->natives->set(zone_, node->fun()->slot(), native);
  1330         return;
  1331     }
  1332 
  1333     // If the function has no body, then it's just a declaration.
  1334     if (!node->body()) {
  1335         assert(node->fun()->isForward() || node->fun()->isPublic());
  1336         return;
  1337     }
  1338 
  1339     BytecodeCompiler child(zone_, tree_, moduleData_);
  1340     Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
  1341     if (!fun)
  1342         return;
  1343     
  1344     assert(!moduleData_->module->getFunction(node->fun()->slot()));
  1345     moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
  1346 }
  1347 
  1348 void
  1349 BytecodeCompiler::visit(FunctionTypeStatement *node)
  1350 {
  1351 }
  1352 
  1353 void
  1354 BytecodeCompiler::visit(EnumStatement *node)
  1355 {
  1356 }
  1357 
  1358 void
  1359 BytecodeCompiler::visit(StructureStatement *node)
  1360 {
  1361 }
  1362 
  1363 void
  1364 BytecodeCompiler::visit(ArrayLiteral *node)
  1365 {
  1366     // We shouldn't reach these; they're handled manually when initializing
  1367     // declared arrays.
  1368     assert(false);
  1369 }
  1370 
  1371 Code *
  1372 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
  1373 {
  1374     // STOP doubles as RETURNVOID.
  1375     __ stop();
  1376 
  1377     if (__ oom() || zone_->hasPendingException())
  1378         return NULL;
  1379 
  1380     Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
  1381     if (!bytes)
  1382         return NULL;
  1383     memcpy(bytes->raw(), __ buffer(), __ length());
  1384 
  1385     for (size_t i = 0; i < scope->maxContainedLocals(); i++)
  1386         assert(locals_->at(i));
  1387 
  1388     Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
  1389     if (!objects)
  1390         return NULL;
  1391 
  1392     for (size_t i = 0; i < __ objects()->length(); i++)
  1393         objects->set(zone_, i, *(__ objects()->at(i)));
  1394 
  1395     Local<ByteArray> safepoints(zone_);
  1396 
  1397     // If any stack slots hold gc pointers at potential failure points in the
  1398     // bytecode, record them now. We do this by building a list of tuples;
  1399     // each tuple contains the pc offset, and a bitset containing which stack
  1400     // slots must be scanned by the gc.
  1401     if (__ oopRecords()->length()) {
  1402         size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
  1403         size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
  1404         safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
  1405         if (!safepoints)
  1406             return NULL;
  1407 
  1408         Address cursor = safepoints->raw();
  1409         for (size_t i = 0; i < __ oopRecords()->length(); i++) {
  1410             OopRecord *record = __ oopRecords()->at(i);
  1411             assert(record->depth <= __ maxStackDepth());
  1412 
  1413             *reinterpret_cast<unsigned *>(cursor) = record->offset;
  1414 
  1415             unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
  1416             for (unsigned i = 0; i < record->depth; i++)
  1417                 bits[i / 8] |= (1 << (i % 8));
  1418 
  1419             cursor += bytesPerSafepoint;
  1420         }
  1421 
  1422         assert(cursor == safepoints->raw() + gcmapSize);
  1423     }
  1424 
  1425     Local<ByteArray> sourcemap(zone_);
  1426     if (__ sourcemapLength()) {
  1427         sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
  1428         if (!sourcemap)
  1429             return NULL;
  1430 
  1431         memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
  1432     }
  1433 
  1434     Local<Code> code(zone_);
  1435 
  1436     code = Code::New(zone_,
  1437                      bytes,
  1438                      locals_,
  1439                      objects,
  1440                      __ maxStackDepth(),
  1441                      moduleData_->module,
  1442                      safepoints,
  1443                      sourcemap,
  1444                      lineno);
  1445     return code;
  1446 }
  1447 
  1448 Function *
  1449 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
  1450 {
  1451     // Note: No need to record a life slot here, since it's part of the Frame.
  1452     AutoEnterScope functionScope(this, node->scope());
  1453 
  1454     // Set the initial line, because line mappings are deltas.
  1455     __ setFirstLine(node->pos().line);
  1456     locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
  1457 
  1458     node->body()->accept(this);
  1459 
  1460     unsigned nargs = node->scope()->numArguments();
  1461     Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
  1462     if (!args)
  1463         return NULL;
  1464 
  1465     for (size_t i = 0; i < node->scope()->numArguments(); i++)
  1466         args->set(zone_, i, node->scope()->getArgument(i)->type());
  1467 
  1468 
  1469     Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
  1470     if (!code)
  1471         return NULL;
  1472 
  1473     Local<Type> type(zone_, node->fun()->type());
  1474     Local<String> name(zone_, node->fun()->name());
  1475     Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
  1476     if (!fun)
  1477         return NULL;
  1478 
  1479     // If this function had a forward, export it as a named public.
  1480     if (node->fun()->isPublic()) {
  1481         assert(node->fun()->isPublic());
  1482         ScopedRoot<Function> root(fun);
  1483         if (!root)
  1484             return NULL;
  1485         if (!moduleData_->publics.append(root))
  1486             return NULL;
  1487     }
  1488 
  1489 #ifndef NDEBUG
  1490     Disassemble(code, stdout);
  1491 #endif
  1492     
  1493     return fun;
  1494 }
  1495 
  1496 Module *
  1497 BytecodeCompiler::compile()
  1498 {
  1499     AutoEnterScope scope(this, tree_->scope());
  1500 
  1501     ModuleData moduleData;
  1502 
  1503     moduleData_ = &moduleData;
  1504     moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
  1505 
  1506     if (!moduleData_)
  1507         return NULL;
  1508     
  1509     moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
  1510     if (!moduleData_->natives)
  1511         return NULL;
  1512 
  1513     for (size_t i = 0; i < tree_->statements()->length(); i++) {
  1514         Statement *statement = tree_->statements()->at(i);
  1515         statement->accept(this);
  1516     }
  1517 
  1518     if (zone_->hasPendingException())
  1519         return NULL;
  1520 
  1521 #ifndef NDEBUG
  1522     for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
  1523         assert(moduleData_->module->getFunction(i));
  1524     for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
  1525         assert(moduleData_->natives->at(i));
  1526 #endif
  1527 
  1528     if (moduleData_->publics.length()) {
  1529         Local<Function> fun(zone_);
  1530         Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
  1531                                Heap::Tenure_Old));
  1532         if (!list)
  1533             return NULL;
  1534 
  1535         for (size_t i = 0; i < moduleData_->publics.length(); i++)
  1536             list->set(zone_, i, moduleData_->publics[i]);
  1537 
  1538         moduleData_->module->setPublics(list);
  1539     }
  1540 
  1541     moduleData_->module->setNatives(moduleData_->natives);
  1542 
  1543     if (scope_->numEnvironmentVars()) {
  1544         Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
  1545         if (!globalMap)
  1546             return NULL;
  1547 
  1548         Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
  1549         if (!environment)
  1550             return NULL;
  1551 
  1552         moduleData_->module->setEnvironment(environment);
  1553     }
  1554 
  1555     Local<Code> code(zone_, compileCode(tree_->scope(), 1));
  1556     if (!code)
  1557         return NULL;
  1558 
  1559     Disassemble(code, stdout);
  1560 
  1561     moduleData_->module->setCode(code);
  1562 
  1563     return moduleData_->module;
  1564 }