src/BytecodeCompiler.cpp
author David Anderson <dvander@alliedmods.net>
Mon Jul 30 12:13:22 2012 -0700 (2012-07-30)
changeset 142 a000bafece09
parent 137 be919b22085b
child 143 393f1b8ac8c3
permissions -rw-r--r--
Implement re-tag unary expression.
     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 "Heap-inl.h"
    29 
    30 using namespace ke;
    31 
    32 typedef BytecodeEmitter::Label Label;
    33 
    34 #define __ emitter_.
    35 
    36 BytecodeCompiler::BytecodeCompiler(Zone *zone, ParseTree *tree, ModuleData *module)
    37   : zone_(zone),
    38     tree_(tree),
    39     emitter_(zone->pool()),
    40     locals_(NULL),
    41     scope_(NULL),
    42     moduleData_(module),
    43     loop_(NULL)
    44 {
    45 }
    46 
    47 static inline TokenKind
    48 ToCompare(Expression *expr)
    49 {
    50     if (expr->isBinaryExpression()) {
    51         BinaryExpression *b = expr->toBinaryExpression();
    52         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
    53             return b->token();
    54     } else if (expr->isUnaryExpression()) {
    55         UnaryExpression *u = expr->toUnaryExpression();
    56         if (u->token() == TOK_NOT)
    57             return TOK_NOT;
    58     }
    59     return TOK_EOF;
    60 }
    61 
    62 static inline Opcode
    63 CompareTokenToJump(TokenKind kind)
    64 {
    65     switch (kind) {
    66       case TOK_EQUALS:
    67         return OP_JEQ;
    68       case TOK_NOTEQUALS:
    69         return OP_JNE;
    70       case TOK_GT:
    71         return OP_JG;
    72       case TOK_GE:
    73         return OP_JGE;
    74       case TOK_LT:
    75         return OP_JL;
    76       default:
    77         assert(kind == TOK_LE);
    78         return OP_JLE;
    79     }
    80 }
    81 
    82 static inline Opcode
    83 TokenToOpcode(TokenKind kind)
    84 {
    85     switch (kind) {
    86       case TOK_PLUS:
    87         return OP_ADD;
    88       case TOK_MINUS:
    89         return OP_SUB;
    90       case TOK_STAR:
    91         return OP_MUL;
    92       case TOK_SLASH:
    93         return OP_DIV;
    94       case TOK_PERCENT:
    95         return OP_MOD;
    96       case TOK_SHR:
    97         return OP_SHR;
    98       case TOK_USHR:
    99         return OP_USHR;
   100       case TOK_SHL:
   101         return OP_SHL;
   102       case TOK_BITAND:
   103         return OP_BITAND;
   104       case TOK_BITOR:
   105         return OP_BITOR;
   106       case TOK_GT:
   107           return OP_GT;
   108       case TOK_GE:
   109           return OP_GE;
   110       case TOK_LT:
   111           return OP_LT;
   112       case TOK_LE:
   113           return OP_LE;
   114       case TOK_EQUALS:
   115           return OP_EQ;
   116       case TOK_NOTEQUALS:
   117           return OP_NE;
   118       default:
   119         assert(kind == TOK_BITXOR);
   120         return OP_BITXOR;
   121     }
   122 }
   123 
   124 void
   125 BytecodeCompiler::recordLifoSlot(Scope *scope)
   126 {
   127     if (!scope)
   128         return;
   129 
   130     if (Variable *var = scope->lifoSlot()) {
   131         locals_->set(zone_, var->slot(), var->type());
   132         __ savelifo(var->slot());
   133     }
   134 }
   135 
   136 void
   137 BytecodeCompiler::unwindTo(Scope *scope)
   138 {
   139     // Note: we only need to unwind to the outermost scope's LIFO slot.
   140     Variable *var = NULL;
   141     for (Scope *current = scope_; current != scope; current = current->enclosing()) {
   142         if (Variable *slot = current->lifoSlot())
   143             var = slot;
   144     }
   145 
   146     if (var)
   147         __ unwindlifo(var->slot());
   148 }
   149 
   150 void
   151 BytecodeCompiler::visit(NameProxy *name)
   152 {
   153     switch (name->binding()->kind()) {
   154       case BoundName::VARIABLE:
   155       {
   156         Variable *var = name->binding()->toVariable();
   157 
   158         if (var->location() == Variable::STACK) {
   159             __ getlocal(var);
   160             assert(!name->type()->isReference());
   161         } else if (var->location() == Variable::ENVIRONMENT) {
   162             getEnvSlot(var);
   163         } else {
   164             assert(var->location() == Variable::PARAMETER);
   165             __ getarg(var);
   166 
   167             // If this argument is actually a reference, dereference it now.
   168             if (var->type()->isReference())
   169                 __ getref(var->type()->contained()->primitive());
   170         }
   171         break;
   172       }
   173 
   174       case BoundName::FUNCTION:
   175       {
   176         NamedFunction *fun = name->binding()->toNamedFunction();
   177         __ module();
   178         __ getmodule_fn(fun->slot());
   179         break;
   180       }
   181 
   182       default:
   183       {
   184         NamedConstant *constant = name->binding()->toNamedConstant();
   185         __ int_(constant->value().toInt());
   186         break;
   187       }
   188     }
   189 }
   190 
   191 void
   192 BytecodeCompiler::visit(ExpressionStatement *node)
   193 {
   194     // Expressions leave their value on the top of the stack, so we make sure
   195     // to balance the stack if they're used as a statement.
   196     node->expression()->accept(this);
   197     if (!node->expression()->type()->isVoid())
   198         __ pop();
   199 }
   200 
   201 void
   202 BytecodeCompiler::visit(Assignment *node)
   203 {
   204     // The first step is three sub-steps:
   205     //
   206     //   (1) Bind the left-hand side.
   207     //   -- If a cumulative operation (+=, etc):
   208     //   (2) Save a copy of the binding on the stack.
   209     //   (3) Dereference the binding to get a value.
   210     //
   211     if (node->lvalue()->isNameProxy()) {
   212         NameProxy *proxy = node->lvalue()->toNameProxy();
   213         Variable *var = proxy->binding()->toVariable();
   214 
   215         // Bind.
   216         if (var->type()->isReference() || var->type()->isArray())
   217             __ get(var);
   218 
   219         // Get the value if needed.
   220         if (node->token() != TOK_ASSIGN) {
   221             // += etc is not allowed on arrays.
   222             assert(!var->type()->isArray());
   223 
   224             if (var->type()->isReference()) {
   225                 __ dup();
   226                 __ getref(var->type()->contained()->primitive());
   227             } else {
   228                 __ get(var);
   229             }
   230         }
   231     } else {
   232         IndexExpression *index = node->lvalue()->toIndexExpression();
   233         __ note_position(index->pos());
   234 
   235         // Note: Eventually, watch out for a whole here. An expression like:
   236         //
   237         //   (a[4] = (5, a = []))
   238         //
   239         // Could shrink array, so we need to either bind a[i] to a Reference,
   240         // or keep the bounds check near the set. This is just a semantic
   241         // decision.
   242         index->left()->accept(this);
   243         index->right()->accept(this);
   244 
   245         if (node->token() != TOK_ASSIGN) {
   246             __ dup2();
   247             __ bounds();
   248             if (node->type()->isArray())
   249                 __ getarray_o();
   250             else
   251                 __ getarray(node->type()->primitive());
   252         }
   253     }
   254 
   255     if (node->token() == TOK_ASSIGN) {
   256         node->expression()->accept(this);
   257     } else {
   258         visitForALU(node->type(), node->expression());
   259 
   260         TokenKind alu = TokenKind(int(node->token()) - (TOK_ASSIGN_ADD - TOK_PLUS));
   261         __ note_position(node->pos());
   262         __ binary(TokenToOpcode(alu));
   263     }
   264 
   265     // Emit the store.
   266     if (node->expression()->type()->isArray()) {
   267         // Unlike references, which can only be computed from a NamePRoxy,
   268         // arrays can be computed from multiple lvalue types.
   269         __ note_position(node->pos());
   270         __ arraycopy();
   271     } else if (node->lvalue()->isNameProxy()) {
   272         NameProxy *proxy = node->lvalue()->toNameProxy();
   273         Variable *var = proxy->binding()->toVariable();
   274 
   275         if (var->type()->isReference())
   276             __ setref(var->type()->contained()->primitive());
   277         else
   278             __ set(var);
   279     } else {
   280         IndexExpression *index = node->lvalue()->toIndexExpression();
   281         // :TODO: get rid of the BOUNDS instruction, embed it in g/setarray*?
   282         // We can't emit it here because the stack is slightly out of position.
   283         // __ bounds();
   284         __ setarray(index->left()->type()->contained()->primitive());
   285     }
   286 }
   287 
   288 void
   289 BytecodeCompiler::visit(IncDecExpression *node)
   290 {
   291     // In the postfix case, the logic looks like:
   292     //      (1) Bind       -> REF
   293     //      (2) Dup        -> REF REF
   294     //      (3) Fetch      -> REF VAL
   295     //      (4) Swap       -> VAL REF
   296     //      (5) Pick       -> VAL REF VAL
   297     //      (6) Add        -> VAL REF VAL+1
   298     //      (7) Store      -> VAL VAL+1
   299     //      (8) Drop       -> VAL
   300     //
   301     // In the prefix case, the logic looks like:
   302     //      (1) Bind       -> REF
   303     //      (2) Dup        -> REF REF
   304     //      (3) Fetch      -> REF VAL
   305     //      --
   306     //      --
   307     //      (6) Add        -> REF VAL+1
   308     //      (7) Store      -> VAL+1
   309     //      --
   310     //
   311     // This is squirrely enough such that we don't bother sharing too much
   312     // with the above.
   313     // 
   314     // Note: We simulate a "Pick" operation with a dup2+pop.
   315 
   316     // This is steps (1) to (5).
   317     Expression *expr = node->expression();
   318     if (expr->isNameProxy()) {
   319         NameProxy *proxy = expr->toNameProxy();
   320         Variable *var = proxy->binding()->toVariable();
   321 
   322         // Bind.
   323         if (var->type()->isReference() || var->type()->isArray())
   324             __ get(var);
   325 
   326         // Dup and fetch.
   327         if (var->type()->isReference()) {
   328             __ dup();
   329             __ getref(node->type()->primitive());
   330             if (node->postfix()) {
   331                 __ swap();
   332                 __ pick2();
   333             }
   334         } else {
   335             assert(!var->type()->isArray());
   336             __ get(var);
   337             if (node->postfix())
   338                 __ dup();
   339         }
   340     } else {
   341         IndexExpression *index = expr->toIndexExpression();
   342         __ note_position(index->pos());
   343 
   344         index->left()->accept(this);
   345         index->right()->accept(this);
   346 
   347         assert(!node->type()->isArray());
   348         __ bounds();
   349         __ dup2();
   350         __ getarray(node->type()->primitive());
   351 
   352         if (node->postfix()) {
   353             // The stack looks like this now:
   354             // ARRAY INDEX VALUE
   355             //
   356             // So we must use a PICK operation to rotate the stack into position.
   357             __ roll3();         // INDEX VALUE ARRAY
   358             __ roll3();         // VALUE ARRAY INDEX
   359             __ pick3();         // VALUE ARRAY INDEX VALUE
   360         }
   361     }
   362 
   363     // Perform step (6).
   364     if (node->type()->isFloat()) {
   365         __ float_(1.0);
   366     } else {
   367         assert(node->type()->isInt32());
   368         __ int_(1);
   369     }
   370 
   371     __ note_position(node->pos());
   372     if (node->token() == TOK_INCREMENT)
   373         __ binary(OP_ADD);
   374     else
   375         __ binary(OP_SUB);
   376 
   377     // Perform step (7).
   378     if (expr->isNameProxy()) {
   379         NameProxy *proxy = expr->toNameProxy();
   380         Variable *var = proxy->binding()->toVariable();
   381 
   382         if (var->type()->isReference())
   383             __ setref(node->type()->primitive());
   384         else
   385             __ set(var);
   386     } else {
   387         __ setarray(node->type()->primitive());
   388     }
   389 
   390     // Perform step (8).
   391     if (node->postfix())
   392         __ pop();
   393 }
   394 
   395 void
   396 BytecodeCompiler::visitForALU(Type *needed, Expression *node)
   397 {
   398     node->accept(this);
   399     if (needed->isFloat() && !node->type()->isFloat())
   400         __ cvt_i2f();
   401     else
   402         assert(needed->primitive() == node->type()->primitive());
   403 }
   404 
   405 static inline Type *
   406 GetCoercionType(TokenKind tok, Type *left, Type *right)
   407 {
   408     if (left->isFloat())
   409         return left;
   410     return right;
   411 }
   412 
   413 void
   414 BytecodeCompiler::visit(UnaryExpression *node)
   415 {
   416     switch (node->token()) {
   417       case TOK_MINUS:
   418       {
   419         Local<Type> type(zone_, node->expression()->type());
   420         node->expression()->accept(this);
   421         
   422         if (node->type()->isFloat())
   423             __ neg_f();
   424         else
   425             __ neg();
   426         break;
   427       }
   428 
   429       case TOK_NOT:
   430       {
   431         Local<Type> type(zone_, node->expression()->type());
   432         node->expression()->accept(this);
   433         
   434         if (node->type()->isFloat())
   435             __ not_f();
   436         else
   437             __ not_();
   438         break;
   439       }
   440 
   441       case TOK_LABEL:
   442       {
   443         Local<Type> from(zone_, node->expression()->type());
   444         Local<Type> to(zone_, node->type());
   445 
   446         node->expression()->accept(this);
   447         if (!from->isFloat() && to->isFloat())
   448             __ bits_f2i();
   449         else if (from->isFloat() && !to->isFloat())
   450             __ bits_i2f();
   451         break;
   452       }
   453 
   454       default:
   455         assert(node->token() == TOK_TILDE);
   456         node->expression()->accept(this);
   457         __ bitnot();
   458         break;
   459     }
   460 }
   461 
   462 void
   463 BytecodeCompiler::visit(BinaryExpression *node)
   464 {
   465     if (node->token() == TOK_AND || node->token() == TOK_OR) {
   466         Label success, failure, done;
   467         visitForTest(node, &success, &failure, &success);
   468         __ bind(&success);
   469         __ int_(1);
   470         __ drop(1);         // Otherwise, the stack depth will be +1 too much.
   471         __ jump(&done);
   472         __ bind(&failure);
   473         __ int_(0);
   474         __ bind(&done);
   475         return;
   476     }
   477 
   478     Local<Type> leftType(zone_, node->left()->type());
   479     Local<Type> rightType(zone_, node->right()->type());
   480     Local<Type> coerce(zone_, GetCoercionType(node->token(), leftType, rightType));
   481 
   482     visitForALU(coerce, node->left());
   483     visitForALU(coerce, node->right());
   484 
   485     Opcode op = TokenToOpcode(node->token());
   486     if (node->type()->isFloat())
   487         op = (Opcode)(int(op) + (OP_ADD_F - OP_ADD));
   488 
   489     __ note_position(node->pos());
   490     __ binary(op);
   491 }
   492 
   493 void
   494 BytecodeCompiler::visit(IndexExpression *node)
   495 {
   496     node->left()->accept(this);
   497     node->right()->accept(this);
   498     __ note_position(node->pos());
   499     __ bounds();
   500 
   501     if (node->type()->isArray())
   502         __ getarray_o();
   503     else
   504         __ getarray(node->type()->primitive());
   505 }
   506 
   507 void
   508 BytecodeCompiler::visit(ReturnStatement *node)
   509 {
   510     if (node->expression()) {
   511         node->expression()->accept(this);
   512         __ return_();
   513     } else {
   514         __ returnvoid();
   515     }
   516 }
   517 
   518 void
   519 BytecodeCompiler::visitForTest(Expression *expression,
   520                                Label *trueBranch,
   521                                Label *falseBranch,
   522                                Label *fallthrough)
   523 {
   524     TokenKind token = ToCompare(expression);
   525     if (token == TOK_EOF || token == TOK_NOT) {
   526         if (token == TOK_EOF)
   527             expression->accept(this);
   528         else
   529             expression->toUnaryExpression()->expression()->accept(this);
   530         
   531         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   532 
   533         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   534         if (expression->type()->isFloat())
   535             op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   536 
   537         if (fallthrough == falseBranch)
   538             __ j(op, trueBranch);
   539         else
   540             __ j(op, falseBranch); 
   541         return;
   542     }
   543 
   544     BinaryExpression *binary = expression->toBinaryExpression();
   545 
   546     if (token == TOK_AND || token == TOK_OR) {
   547         Label next;
   548         if (token == TOK_AND)
   549             visitForTest(binary->left(), &next, falseBranch, &next);
   550         else
   551             visitForTest(binary->left(), trueBranch, &next, &next);
   552         __ bind(&next);
   553         visitForTest(binary->right(), trueBranch, falseBranch, fallthrough);
   554         return;
   555     }
   556 
   557     Opcode op = CompareTokenToJump(token);
   558     if (fallthrough == trueBranch)
   559         op = Invert(op);
   560 
   561     Local<Type> leftType(zone_, binary->left()->type());
   562     Local<Type> rightType(zone_, binary->right()->type());
   563     Local<Type> coerce(zone_, GetCoercionType(binary->token(), leftType, rightType));
   564 
   565     visitForALU(coerce, binary->left());
   566     visitForALU(coerce, binary->right());
   567     if (coerce->isFloat())
   568         op = (Opcode)(int(op) + (OP_JL_F - OP_JL));
   569 
   570     if (fallthrough == trueBranch)
   571         __ j(op, falseBranch);
   572     else
   573         __ j(op, trueBranch);
   574 }
   575 
   576 void
   577 BytecodeCompiler::visit(ForStatement *node)
   578 {
   579     AutoEnterScope forScope(this, node->scope());
   580 
   581     recordLifoSlot(node->scope());
   582 
   583     Label join, update;
   584     LoopScope loop(scope_, &join, &update, &loop_);
   585 
   586     if (node->initialization())
   587         node->initialization()->accept(this);
   588 
   589     Label header, test;
   590     if (node->condition())
   591         __ jump(&test);
   592 
   593     __ bind(&header);
   594     node->body()->accept(this);
   595 
   596     __ bind(&update);
   597     if (node->update())
   598         node->update()->accept(this);
   599 
   600     if (node->condition()) {
   601         __ bind(&test);
   602         visitForTest(node->condition(), &header, &join, &join);
   603     } else {
   604         __ jump(&header);
   605     }
   606 
   607     __ bind(&join);
   608 
   609     if (node->scope())
   610         unwindTo(node->scope()->enclosing());
   611     assert(__ stackDepth() == 0);
   612 }
   613 
   614 void
   615 BytecodeCompiler::visit(WhileStatement *node)
   616 {
   617     Label header, join;
   618 
   619     __ bind(&header);
   620 
   621     LoopScope loop(scope_, &join, &header, &loop_);
   622 
   623     if (node->token() == TOK_WHILE) {
   624         Label body;
   625 
   626         visitForTest(node->condition(), &body, &join, &body);
   627         __ bind(&body);
   628         node->body()->accept(this);
   629         __ jump(&header);
   630     } else {
   631         node->body()->accept(this);
   632         visitForTest(node->condition(), &header, &join, &join);
   633     }
   634 
   635     __ bind(&join);
   636 }
   637 
   638 void
   639 BytecodeCompiler::visit(BreakStatement *node)
   640 {
   641     unwindTo(loop_->scope());
   642     __ jump(loop_->break_());
   643 }
   644 
   645 void
   646 BytecodeCompiler::visit(ContinueStatement *node)
   647 {
   648     unwindTo(loop_->scope());
   649     __ jump(loop_->continue_());
   650 }
   651 
   652 void
   653 BytecodeCompiler::visit(BlockStatement *node)
   654 {
   655     AutoEnterScope blockScope(this, node->scope());
   656 
   657     recordLifoSlot(node->scope());
   658 
   659     for (size_t i = 0; i < node->statements()->length(); i++) {
   660         Statement *statement = node->statements()->at(i);
   661         statement->accept(this);
   662         assert(__ stackDepth() == 0);
   663     }
   664 
   665     // We don't bother emitting an "unwind" instruction for function scopes,
   666     // since this is taken care of by the calling convention.
   667     if (node->scope() && node->scope()->enclosing()->kind() != Scope::FUNCTION)
   668         unwindTo(node->scope()->enclosing());
   669 }
   670 
   671 void
   672 BytecodeCompiler::visit(IntegerLiteral *node)
   673 {
   674     __ int_(node->value());
   675 }
   676 
   677 void
   678 BytecodeCompiler::visit(FloatLiteral *node)
   679 {
   680     __ float_((float)node->value());
   681 }
   682 
   683 static inline ArrayMap *
   684 BuildArrayMap(Zone *zone, Handle<Type> type)
   685 {
   686     Local<ArrayMap> contained(zone);
   687     if (type->levels() > 1) {
   688         Local<Type> containedType(zone, type->contained());
   689         contained = BuildArrayMap(zone, containedType);
   690         if (!contained)
   691             return NULL;
   692     }
   693 
   694     return ArrayMap::New(zone, type, contained);
   695 }
   696 
   697 void
   698 BytecodeCompiler::visit(StringLiteral *node)
   699 {
   700     Local<Type> type(zone_, node->type());
   701     Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
   702     if (!map)
   703         return;
   704 
   705     Local<Array> array(zone_, Array::New(zone_, map, node->string()->length(), Heap::Tenure_Old));
   706     if (!array)
   707         return;
   708 
   709     assert(array->nelements() >= node->string()->length());
   710     memcpy(array->chars(), node->string()->raw(), node->string()->length() * sizeof(char));
   711 
   712     __ note_position(node->pos());
   713     __ object(array);
   714 }
   715 
   716 void
   717 BytecodeCompiler::getEnvSlot(Variable *var)
   718 {
   719     assert(var->scope()->kind() == Scope::GLOBAL);
   720     __ getglobal(var);
   721 }
   722 
   723 void
   724 BytecodeCompiler::setEnvSlot(Variable *var)
   725 {
   726     assert(var->scope()->kind() == Scope::GLOBAL);
   727     __ setglobal(var);
   728 }
   729 
   730 void
   731 BytecodeCompiler::visit(VariableDeclaration *node)
   732 {
   733     Variable *var = node->variable();
   734     
   735     Local<Type> type(zone_, var->type());
   736     if (type->isArray()) {
   737         Local<ArrayMap> map(zone_, BuildArrayMap(zone_, type));
   738         __ note_position(node->pos());
   739         if (var->scope()->kind() == Scope::GLOBAL)
   740             __ newarray(map, Heap::Tenure_Old);
   741         else if (var->needsHeapAllocation())
   742             __ newarray(map, Heap::Tenure_Default);
   743         else
   744             __ newarray(map, Heap::Tenure_Stack);
   745 
   746         if (node->initialization()) {
   747             node->initialization()->accept(this);
   748             __ note_position(node->pos());
   749             __ arraycopy();
   750         }
   751     } else {
   752         if (node->initialization()) {
   753             node->initialization()->accept(this);
   754         } else {
   755             if (!node->postDimensions())
   756                 __ int_(0);
   757         }
   758     }
   759 
   760     if (var->location() == Variable::STACK) {
   761         __ setlocal(var);
   762         locals_->set(zone_, var->slot(), var->type());
   763     } else {
   764         assert(var->location() == Variable::ENVIRONMENT);
   765         setEnvSlot(var);
   766     }
   767 
   768     __ pop();
   769 }
   770 
   771 void
   772 BytecodeCompiler::visit(CallExpression *node)
   773 {
   774     Local<Type> funType(zone_, node->callee()->type());
   775 
   776     // Sniff out natives, which have a specific opcode and are guaranteed to
   777     // be called via name proxy.
   778     NamedFunction *native = NULL;
   779     if (funType->isNative()) {
   780         native = node->callee()->toNameProxy()->binding()->toNamedFunction();
   781     }
   782 
   783     for (size_t i = node->arguments()->length() - 1; i < node->arguments()->length(); i--) {
   784         Expression *arg = node->arguments()->at(i);
   785 
   786         // We need to compute a reference if the parameter was in the form:
   787         //  f(&a)
   788         // Note this form does not allow: f({})
   789         // 
   790         // We also need to compute references for all variadic native
   791         // arguments, but arrays and references are already in the
   792         // appropriate form.
   793         Local<Type> given(zone_, arg->type());
   794         bool mustPushReference = false;
   795         if (i >= funType->parameters()->length()) {
   796             assert(funType->isNative() && funType->isNativeVariadic());
   797             mustPushReference = !given->isArray() && !given->isReference();
   798         } else if (funType->parameterAt(i)->isReference()) {
   799             mustPushReference = !given->isReference();
   800         }
   801 
   802         // If a native is passed to a native, it must only be one level deep.
   803         assert(!funType->isNative() || !given->isArray() || given->levels() == 1);
   804 
   805         if (mustPushReference) {
   806             if (arg->isNameProxy()) {
   807                 // :TODO: test with functions and globals
   808                 // Compute a reference to the name.
   809                 Variable *var = arg->toNameProxy()->binding()->toVariable();
   810                 __ note_position(node->pos());
   811                 __ newref(var);
   812             } else if (arg->isIndexExpression()) {
   813                 IndexExpression *expr = arg->toIndexExpression();
   814                 expr->left()->accept(this);
   815                 expr->right()->accept(this);
   816                 __ note_position(expr->pos());
   817                 __ bounds();
   818                 __ arrayref_lifo();
   819             } else {
   820                 // We don't know how to, or can't, build a direct reference to
   821                 // this type. Make an indirect one, by taking the top of the
   822                 // stack and boxing it up.
   823                 arg->accept(this);
   824                 __ note_position(node->pos());
   825                 __ slotref_lifo();
   826             }
   827         } else {
   828             arg->accept(this);
   829         }
   830     }
   831 
   832     __ note_position(node->pos());
   833     if (native) {
   834         __ callnative(native->slot(), node->arguments()->length());
   835         __ drop(node->arguments()->length());
   836     } else {
   837         node->callee()->accept(this);
   838         __ call(funType);
   839         __ drop(node->arguments()->length() + 1);
   840     }
   841 }
   842 
   843 void
   844 BytecodeCompiler::visit(TernaryExpression *node)
   845 {
   846     Label success, failure, join;
   847 
   848     visitForTest(node->condition(), &success, &failure, &success);
   849     __ bind(&success);
   850     node->left()->accept(this);
   851     __ drop(1);
   852     __ jump(&join);
   853     __ bind(&failure);
   854     node->right()->accept(this);
   855     __ bind(&join);
   856 }
   857 
   858 void
   859 BytecodeCompiler::visit(IfStatement *node)
   860 {
   861     Label join;
   862     if (!node->ifFalse()) {
   863         Label success;
   864 
   865         visitForTest(node->condition(), &success, &join, &success);
   866         __ bind(&success);
   867         node->ifTrue()->accept(this);
   868     } else {
   869         Label success, next;
   870 
   871         visitForTest(node->condition(), &success, &next, &success);
   872         __ bind(&success);
   873         node->ifTrue()->accept(this);
   874         __ jump(&join);
   875         __ bind(&next);
   876         node->ifFalse()->accept(this);
   877     }
   878 
   879     __ bind(&join);
   880 }
   881 
   882 void
   883 BytecodeCompiler::visit(FunctionStatement *node)
   884 {
   885     if (!node->fun()->used())
   886         return;
   887 
   888     if (node->fun()->isNative()) {
   889         assert(!moduleData_->natives->at(node->fun()->slot()));
   890 
   891         Local<Type> type(zone_, node->fun()->type());
   892         Local<String> name(zone_, node->fun()->name());
   893         Local<Native> native(zone_, Native::New(zone_, type, name));
   894         if (!native)
   895             return;
   896 
   897         moduleData_->natives->set(zone_, node->fun()->slot(), native);
   898         return;
   899     }
   900 
   901     // If the function has no body, then it's just a declaration.
   902     if (!node->body()) {
   903         assert(node->fun()->isForward() || node->fun()->isPublic());
   904         return;
   905     }
   906 
   907     BytecodeCompiler child(zone_, tree_, moduleData_);
   908     Local<Function> fun(zone_, child.compileFunction(moduleData_, node));
   909     if (!fun)
   910         return;
   911     
   912     assert(!moduleData_->module->getFunction(node->fun()->slot()));
   913     moduleData_->module->setFunction(zone_, node->fun()->slot(), fun);
   914 }
   915 
   916 void
   917 BytecodeCompiler::visit(EnumStatement *node)
   918 {
   919     // :TODO: eventually, we'll export these.
   920 }
   921 
   922 Code *
   923 BytecodeCompiler::compileCode(Scope *scope, unsigned lineno)
   924 {
   925     // STOP doubles as RETURNVOID.
   926     __ stop();
   927 
   928     if (__ oom() || zone_->hasPendingException())
   929         return NULL;
   930 
   931     Local<ByteArray> bytes(zone_, ByteArray::New(zone_, __ length() * sizeof(bytecode), Heap::Tenure_Old));
   932     if (!bytes)
   933         return NULL;
   934     memcpy(bytes->raw(), __ buffer(), __ length());
   935 
   936     for (size_t i = 0; i < scope->maxContainedLocals(); i++)
   937         assert(locals_->at(i));
   938 
   939     Local<FixedArray> objects(zone_, FixedArray::New(zone_, __ objects()->length(), Heap::Tenure_Old));
   940     if (!objects)
   941         return NULL;
   942 
   943     for (size_t i = 0; i < __ objects()->length(); i++)
   944         objects->set(zone_, i, *(__ objects()->at(i)));
   945 
   946     Local<ByteArray> safepoints(zone_);
   947 
   948     // If any stack slots hold gc pointers at potential failure points in the
   949     // bytecode, record them now. We do this by building a list of tuples;
   950     // each tuple contains the pc offset, and a bitset containing which stack
   951     // slots must be scanned by the gc.
   952     if (__ oopRecords()->length()) {
   953         size_t bytesPerSafepoint = Code::BytesPerSafepoint(__ maxStackDepth());
   954         size_t gcmapSize = bytesPerSafepoint * __ oopRecords()->length();
   955         safepoints = ByteArray::New(zone_, gcmapSize, Heap::Tenure_Old);
   956         if (!safepoints)
   957             return NULL;
   958 
   959         Address cursor = safepoints->raw();
   960         for (size_t i = 0; i < __ oopRecords()->length(); i++) {
   961             OopRecord *record = __ oopRecords()->at(i);
   962             assert(record->depth <= __ maxStackDepth());
   963 
   964             *reinterpret_cast<unsigned *>(cursor) = record->offset;
   965 
   966             unsigned char *bits = reinterpret_cast<unsigned char *>(cursor + sizeof(unsigned));
   967             for (unsigned i = 0; i < record->depth; i++)
   968                 bits[i / 8] |= (1 << (i % 8));
   969 
   970             cursor += bytesPerSafepoint;
   971         }
   972 
   973         assert(cursor == safepoints->raw() + gcmapSize);
   974     }
   975 
   976     Local<ByteArray> sourcemap(zone_);
   977     if (__ sourcemapLength()) {
   978         sourcemap = ByteArray::New(zone_, __ sourcemapLength(), Heap::Tenure_Old);
   979         if (!sourcemap)
   980             return NULL;
   981 
   982         memcpy(sourcemap->raw(), __ sourcemap(), __ sourcemapLength());
   983     }
   984 
   985     Local<Code> code(zone_);
   986 
   987     code = Code::New(zone_,
   988                      bytes,
   989                      locals_,
   990                      objects,
   991                      __ maxStackDepth(),
   992                      moduleData_->module,
   993                      safepoints,
   994                      sourcemap,
   995                      lineno);
   996     return code;
   997 }
   998 
   999 Function *
  1000 BytecodeCompiler::compileFunction(ModuleData *module, FunctionStatement *node)
  1001 {
  1002     // Note: No need to record a life slot here, since it's part of the Frame.
  1003     AutoEnterScope functionScope(this, node->scope());
  1004 
  1005     // Set the initial line, because line mappings are deltas.
  1006     __ setFirstLine(node->pos().line);
  1007     locals_ = FixedArray::New(zone_, node->scope()->maxContainedLocals(), Heap::Tenure_Old);
  1008 
  1009     node->body()->accept(this);
  1010 
  1011     unsigned nargs = node->scope()->numArguments();
  1012     Local<FixedArray> args(zone_, FixedArray::New(zone_, nargs, Heap::Tenure_Old));
  1013     if (!args)
  1014         return NULL;
  1015 
  1016     for (size_t i = 0; i < node->scope()->numArguments(); i++)
  1017         args->set(zone_, i, node->scope()->getArgument(i)->type());
  1018 
  1019 
  1020     Local<Code> code(zone_, compileCode(node->scope(), node->pos().line));
  1021     if (!code)
  1022         return NULL;
  1023 
  1024     Local<Type> type(zone_, node->fun()->type());
  1025     Local<String> name(zone_, node->fun()->name());
  1026     Local<Function> fun(zone_, Function::New(zone_, code, type, name, node->pos()));
  1027     if (!fun)
  1028         return NULL;
  1029 
  1030     // If this function had a forward, export it as a named public.
  1031     if (node->fun()->isPublic()) {
  1032         assert(node->fun()->isPublic());
  1033         ScopedRoot<Function> root(fun);
  1034         if (!root)
  1035             return NULL;
  1036         if (!moduleData_->publics.append(root))
  1037             return NULL;
  1038     }
  1039 
  1040     Disassemble(code, stdout);
  1041     
  1042     return fun;
  1043 }
  1044 
  1045 Module *
  1046 BytecodeCompiler::compile()
  1047 {
  1048     AutoEnterScope scope(this, tree_->scope());
  1049 
  1050     ModuleData moduleData;
  1051 
  1052     moduleData_ = &moduleData;
  1053     moduleData_->module = Module::New(zone_, tree_->scope()->numFunctions());
  1054 
  1055     if (!moduleData_)
  1056         return NULL;
  1057     
  1058     moduleData_->natives = FixedArray::New(zone_, tree_->scope()->numNatives(), Heap::Tenure_Old);
  1059     if (!moduleData_->natives)
  1060         return NULL;
  1061 
  1062     for (size_t i = 0; i < tree_->statements()->length(); i++) {
  1063         Statement *statement = tree_->statements()->at(i);
  1064         statement->accept(this);
  1065     }
  1066 
  1067     if (zone_->hasPendingException())
  1068         return NULL;
  1069 
  1070 #ifndef NDEBUG
  1071     for (size_t i = 0; i < tree_->scope()->numFunctions(); i++)
  1072         assert(moduleData_->module->getFunction(i));
  1073     for (size_t i = 0; i < tree_->scope()->numNatives(); i++)
  1074         assert(moduleData_->natives->at(i));
  1075 #endif
  1076 
  1077     if (moduleData_->publics.length()) {
  1078         Local<Function> fun(zone_);
  1079         Local<FixedArray> list(zone_, FixedArray::New(zone_, moduleData_->publics.length(),
  1080                                Heap::Tenure_Old));
  1081         if (!list)
  1082             return NULL;
  1083 
  1084         for (size_t i = 0; i < moduleData_->publics.length(); i++)
  1085             list->set(zone_, i, moduleData_->publics[i]);
  1086 
  1087         moduleData_->module->setPublics(list);
  1088     }
  1089 
  1090     moduleData_->module->setNatives(moduleData_->natives);
  1091 
  1092     if (scope_->numEnvironmentVars()) {
  1093         Local<EnvironmentMap> globalMap(zone_, scope_->createEnvironmentMap(zone_));
  1094         if (!globalMap)
  1095             return NULL;
  1096 
  1097         Local<Environment> environment(zone_, Environment::New(zone_, globalMap));
  1098         if (!environment)
  1099             return NULL;
  1100 
  1101         moduleData_->module->setEnvironment(environment);
  1102     }
  1103 
  1104     Local<Code> code(zone_, compileCode(tree_->scope(), 1));
  1105     if (!code)
  1106         return NULL;
  1107 
  1108     Disassemble(code, stdout);
  1109 
  1110     moduleData_->module->setCode(code);
  1111 
  1112     return moduleData_->module;
  1113 }