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