src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Sat Dec 22 18:22:14 2012 -0800 (2012-12-22)
changeset 230 fb3cd08bc7fb
parent 222 0cde1379b29f
child 232 2b8512340180
permissions -rw-r--r--
Re-add LIFO stack optimizations.
     1 /* vim: set ts=4 sw=4 tw=99 et:
     2  *
     3  * Copyright (C) 2012 David Anderson
     4  *
     5  * This file is part of SourcePawn.
     6  *
     7  * SourcePawn 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  * SourcePawn 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  * SourcePawn. If not, see http://www.gnu.org/licenses/.
    18  */
    19 #include <assert.h>
    20 #include "../Zone.h"
    21 #include "../Strings.h"
    22 #include "../NativeTable.h"
    23 #include "../TypeManager.h"
    24 #include "../Modules.h"
    25 #include "../Code.h"
    26 #include "SemanticAnalysis.h"
    27 #include "../Heap-inl.h"
    28 
    29 using namespace ke;
    30 
    31 #define __ emitter_.
    32 
    33 typedef BytecodeEmitter::Label Label;
    34 
    35 class AutoEnterScope
    36 {
    37   public:
    38     AutoEnterScope(Scope **prevp, Scope *scope)
    39       : prevp_(prevp),
    40         prev_(*prevp),
    41         scope_(scope)
    42     {
    43         if (!scope_)
    44             return;
    45         prev_ = *prevp_;
    46         *prevp_ = scope;
    47         assert(prev_ == scope->enclosing());
    48     }
    49     ~AutoEnterScope()
    50     {
    51         if (scope_)
    52             *prevp_ = prev_;
    53     }
    54   private:
    55     Scope **prevp_;
    56     Scope *prev_;
    57     Scope *scope_;
    58 };
    59 
    60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
    61   : zone_(zone),
    62     pool_(zone->pool()),
    63     cc_(cc),
    64     unit_(unit),
    65     hir_(NULL),
    66     emitter_(pool_),
    67     module_(NULL),
    68     loop_(NULL)
    69 {
    70 }
    71 
    72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
    73   : zone_(parent->zone_),
    74     pool_(parent->pool_),
    75     cc_(parent->cc_),
    76     unit_(parent->unit_),
    77     hir_(NULL),
    78     scope_(parent->scope_),
    79     emitter_(pool_),
    80     module_(parent->module_),
    81     fun_(fun),
    82     loop_(NULL)
    83 {
    84 
    85 }
    86 
    87 void
    88 SemanticAnalysis::analyze()
    89 {
    90     scope_ = unit_->globalScope();
    91 
    92     module_ = Module::New(zone_);
    93 
    94     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    95         Statement *stmt = unit_->tree()->statements()->at(i);
    96         stmt->accept(this);
    97     }
    98 
    99     Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
   100     if (!globals)
   101         return;
   102     module_->setGlobals(globals);
   103 
   104     Local<Code> code(zone_, __ finish());
   105     if (!code)
   106         return;
   107     code->setModule(module_);
   108     module_->setCode(code);
   109 
   110 #ifndef NDEBUG
   111 //    Disassemble(code, stdout);
   112 #endif
   113 
   114     unit_->module_ = module_;
   115 }
   116 
   117 void
   118 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   119 {
   120     FunctionSymbol *sym = stmt->sym();
   121     Local<FunctionType> type(zone_, sym->type());
   122 
   123     assert(scope_->kind() == Scope::GLOBAL);
   124 
   125     if (stmt->token() == TOK_NATIVE) {
   126         // Define the native now.
   127         size_t index;
   128         if (!zone_->nativeTable()->add(stmt->name(), &index))
   129             return;
   130 
   131         Local<Native> native(zone_, Native::New(zone_, type, index));
   132         if (!native)
   133             return;
   134 
   135         __ object(native);
   136         __ setglobal(sym);
   137         __ pop();
   138     }
   139 
   140     // If the function is a forward or native, we don't have to do anything.
   141     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   142         return;
   143 
   144     SemanticAnalysis child(this, type);
   145     Local<Function> funobj(zone_, child.compile(stmt));
   146     if (!funobj)
   147         return;
   148 
   149     __ object(funobj);
   150     __ setglobal(sym);
   151     if (stmt->token() == TOK_PUBLIC)
   152         __ public_();
   153     else
   154         __ pop();
   155 }
   156 
   157 Function *
   158 SemanticAnalysis::compile(FunctionStatement *stmt)
   159 {
   160     __ setFirstLine(stmt->pos().line);
   161 
   162     AutoEnterScope argScope(&scope_, stmt->argScope());
   163 
   164     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   165         Parameter *param = stmt->signature().parameters()->at(i);
   166         param->sym()->allocate(VariableSymbol::Arg, i);
   167     }
   168 
   169     AutoEnterScope varScope(&scope_, stmt->varScope());
   170 
   171     stmt->body()->accept(this);
   172 
   173     Local<Code> code(zone_, __ finish());
   174     if (!code)
   175         return NULL;
   176     code->setModule(module_);
   177 
   178     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   179     if (!fun)
   180         return NULL;
   181 
   182 #ifndef NDEBUG
   183 //    Disassemble(code, stdout);
   184 #endif
   185 
   186     return fun;
   187 }
   188 
   189 void 
   190 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   191 {
   192     AutoEnterScope scope(&scope_, node->scope());
   193 
   194     for (size_t i = 0; i < node->statements()->length(); i++) {
   195         Statement *stmt = node->statements()->at(i);
   196         __ note_position(stmt->pos());
   197         stmt->accept(this);
   198         assert(__ stackDepth() == 0);
   199     }
   200 }
   201 
   202 void
   203 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   204 {
   205     // While building HIR, we enter new pool and root scopes, since HIR
   206     // creation is purely temporary.
   207     PoolScope poolScope(zone_->pool());
   208     RootScope rootScope(zone_);
   209 
   210     HIR *hir = eval(node->expression());
   211     if (!hir)
   212         return;
   213 
   214     discharge(hir);
   215     if (!hir->type()->isVoid())
   216         __ pop();
   217 }
   218 
   219 void
   220 SemanticAnalysis::visitIfStatement(IfStatement *node)
   221 {
   222     Label join;
   223 
   224     if (!node->ifFalse()) {
   225         Label success;
   226 
   227         visitForTest(node->condition(), &success, &join, &success);
   228         __ bind(&success);
   229         node->ifTrue()->accept(this);
   230     } else {
   231         Label success, next;
   232 
   233         visitForTest(node->condition(), &success, &next, &success);
   234         __ bind(&success);
   235         node->ifTrue()->accept(this);
   236         __ jump(&join);
   237         __ bind(&next);
   238         node->ifFalse()->accept(this);
   239     }
   240 
   241     __ bind(&join);
   242 }
   243 
   244 void
   245 SemanticAnalysis::requireLifoStack()
   246 {
   247     if (!loop_)
   248         return;
   249 
   250     loop_->setUsesLifoStack();
   251 }
   252 
   253 void
   254 SemanticAnalysis::visitLoopBody(Statement *stmt)
   255 {
   256     // We always mark off a loop body, so on each edge, we can balance the
   257     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   258     // stack ahead of time. If we turn out to never need the LIFO stack, we
   259     // mark it as unnecessary. (The interpreter can't really make use of this,
   260     // but the JIT can).
   261     //
   262     // Note that balancing the LIFO stack isn't even necessary, so this
   263     // feature may be removed. All this mechanism does is mitigate the
   264     // possibility that a long-running loop will overflow the LIFO region
   265     // and therefore start requiring nursery allocations.
   266     int pos = __ enterloop();
   267     stmt->accept(this);
   268     __ leaveloop();
   269 
   270     if (loop_->usesLifoStack())
   271         __ setLoopUsesLifoStack(pos);
   272 }
   273 
   274 void
   275 SemanticAnalysis::visitForStatement(ForStatement *node)
   276 {
   277     AutoEnterScope scope(&scope_, node->scope());
   278     PoolScope poolScope(zone_->pool());
   279     RootScope rootScope(zone_);
   280 
   281     Label join, update;
   282     LoopScope loop(scope_, &join, &update, &loop_);
   283 
   284     if (node->initialization())
   285         node->initialization()->accept(this);
   286 
   287     Label header, test;
   288     if (node->condition())
   289         __ jump(&test);
   290 
   291     __ bind(&header);
   292     visitLoopBody(node->body());
   293 
   294     __ bind(&update);
   295     if (node->update())
   296         node->update()->accept(this);
   297 
   298     if (node->condition()) {
   299         __ bind(&test);
   300         visitForTest(node->condition(), &header, &join, &join);
   301     } else {
   302         __ jump(&header);
   303     }
   304 
   305     __ bind(&join);
   306 
   307     assert(__ stackDepth() == 0);
   308 }
   309 
   310 void
   311 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   312 {
   313     PoolScope poolScope(zone_->pool());
   314     RootScope rootScope(zone_);
   315 
   316     Label header, join;
   317 
   318     __ bind(&header);
   319 
   320     LoopScope loop(scope_, &join, &header, &loop_);
   321     if (node->token() == TOK_WHILE) {
   322         Label body;
   323         visitForTest(node->condition(), &body, &join, &body);
   324         visitLoopBody(node->body());
   325         __ jump(&header);
   326     } else {
   327         visitLoopBody(node->body());
   328         visitForTest(node->condition(), &header, &join, &join);
   329     }
   330 
   331     __ bind(&join);
   332 
   333     assert(__ stackDepth() == 0);
   334 }
   335 
   336 static inline Heap::Tenure
   337 InferTenure(Symbol *sym)
   338 {
   339     if (sym->scope()->kind() == Scope::GLOBAL)
   340         return Heap::Tenure_Old;
   341 
   342     // SP2's array semantics allow any array kind to escape, so we must use
   343     // the normal heap. (Hopefully escape analysis can ease this pain later).
   344     if (sym->type()->isArray())
   345         return Heap::Tenure_Default;
   346 
   347     return Heap::Tenure_Default;
   348 }
   349 
   350 void
   351 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   352 {
   353     PoolScope poolScope(zone_->pool());
   354     RootScope rootScope(zone_);
   355 
   356     if (node->initialization()) {
   357         HIR *hir = NULL;
   358 
   359         if ((hir = eval(node->initialization())) == NULL)
   360             return;
   361         if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
   362             return;
   363 
   364         discharge(hir);
   365     } else {
   366         if (node->sym()->type()->isInt32() ||
   367             node->sym()->type()->isEnum() ||
   368             node->sym()->type()->isChar() ||
   369             node->sym()->type()->isBool())
   370         {
   371             __ int_(0);
   372         } else if (node->sym()->type()->isFloat()) {
   373             __ float_(0);
   374         } else if (node->sym()->type()->isArray()) {
   375             Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
   376             Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
   377             if (!map)
   378                 return;
   379 
   380             if (type->isFixedLength()) {
   381                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   382             } else if (node->dims()) {
   383                 assert(false);
   384                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   385             } else {
   386                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   387             }
   388         }
   389     }
   390 
   391     if (!__ allocate(node->sym()))
   392         return;
   393 
   394     set(node->sym());
   395     __ pop();
   396 }
   397 
   398 void
   399 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   400 {
   401     if (!node->expression()) {
   402         if (!fun_->returnType()->isVoid()) {
   403             cc_.reportError(node->pos(), Message_UsedVoidReturn);
   404             return;
   405         }
   406 
   407         __ returnvoid();
   408         return;
   409     }
   410 
   411     PoolScope poolScope(zone_->pool());
   412     RootScope rootScope(zone_);
   413 
   414     HIR *hir = eval(node->expression());
   415     if (!hir)
   416         return;
   417 
   418     Local<Type> returnType(zone_, fun_->returnType());
   419     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   420         return;
   421 
   422     discharge(hir);
   423     __ return_();
   424 }
   425 
   426 void
   427 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   428 {
   429     HIR *left = eval(node->left());
   430     HIR *right = eval(node->right());
   431     if (!left || !right)
   432         return;
   433 
   434     hir_ = binary(node, node->token(), left, right);
   435 }
   436 
   437 bool
   438 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   439 {
   440     if (type->parameters()->length() == actual)
   441         return true;
   442 
   443     if (actual > type->parameters()->length()) {
   444         if (!type->isNative() || !type->isNativeVariadic())
   445             return false;
   446         return true;
   447     }
   448 
   449     if (!type->defaults())
   450         return false;
   451 
   452     // Missing arguments. See if there's a default argument for each missing
   453     // actual.
   454     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   455         if (!type->defaults()->at(i))
   456             return false;
   457     }
   458 
   459     return true;
   460 }
   461 
   462 void
   463 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   464 {
   465     Symbol *sym = proxy->sym();
   466     VariableSymbol *var = sym->asVariable();
   467 
   468     Scope *in = sym->scope();
   469     switch (in->kind()) {
   470       case Scope::GLOBAL:
   471         hir_ = new (pool_) HGlobal(proxy, sym);
   472         return;
   473 
   474       case Scope::FUNCTION:
   475         assert(var->storage() == VariableSymbol::Arg);
   476         hir_ = new (pool_) HLocal(proxy, var);
   477         return;
   478 
   479       default:
   480         assert(in->kind() == Scope::BLOCK);
   481         assert(var->storage() == VariableSymbol::Local);
   482         hir_ = new (pool_) HLocal(proxy, var);
   483         return;
   484     }
   485 }
   486 
   487 void
   488 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   489 {
   490     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   491     hir_ = new (pool_) HInteger(lit, type, lit->value());
   492 }
   493 
   494 void
   495 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   496 {
   497     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   498     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   499 }
   500 
   501 void
   502 SemanticAnalysis::visitCallExpression(CallExpression *node)
   503 {
   504     HIR *callee = eval(node->callee());
   505     if (!callee)
   506         return;
   507 
   508     if (!callee->type()->isFunction()) {
   509         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   510         return;
   511     }
   512 
   513     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   514     
   515     if (!checkArgumentCount(fun, node->arguments()->length())) {
   516         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   517         return;
   518     }
   519 
   520     if (fun->isForward()) {
   521         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   522         return;
   523     }
   524 
   525     HIRList *args = new (pool_) HIRList;
   526     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   527         Expression *expression = node->arguments()->at(i);
   528         HIR *arg = eval(expression);
   529         if (!arg)
   530             return;
   531 
   532         Handle<Type> given = arg->type();
   533         
   534         bool mustComputeReference;
   535         if (i >= fun->parameters()->length()) {
   536             // Special handling for natives. Arguments past the formal must
   537             // always have references computed. However, arrays are already
   538             // references for natives.
   539             assert(fun->isNative() && fun->isNativeVariadic());
   540             mustComputeReference = !given->isReference() &&
   541                                    !given->isArray();
   542         } else {
   543             Local<Type> actual(zone_, fun->parameterAt(i));
   544 
   545             if (expression->isIndexExpression()) {
   546                 // Temporarily disabled.
   547                 assert(!actual->isArray());
   548                 if (actual->isReference()) {
   549                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   550                     return;
   551                 }
   552             }
   553 
   554             if (actual->isReference()) {
   555                 // If the actual is a reference, the coercion rules are much
   556                 // stricter; the contained types must be identical.
   557                 // :TODO: make this not an assert
   558                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   559             } else {
   560                 // When we start overloading, coercion will have to happen later.
   561                 arg = coerce(arg, actual, Coerce_Arg);
   562                 if (!arg)
   563                     return;
   564             }
   565 
   566             mustComputeReference = actual->isReference() && !given->isReference();
   567         }
   568 
   569         if (mustComputeReference) {
   570             // Refs always use the LIFO stack if they can.
   571             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   572             requireLifoStack();
   573         }
   574 
   575         if (!args->append(arg))
   576             return;
   577     }
   578 
   579     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   580 }
   581 
   582 void
   583 SemanticAnalysis::visitAssignment(Assignment *node)
   584 {
   585     HLValue *lval = lvalue(node->lvalue());
   586     if (!lval)
   587         return;
   588 
   589     HIR *hir = eval(node->expression());
   590     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   591         return;
   592 
   593     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   594 }
   595 
   596 void
   597 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   598 {
   599     if (!loop_) {
   600         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   601         return;
   602     }
   603 
   604     __ j(OP_BREAK, loop_->break_());
   605 }
   606 
   607 void
   608 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   609 {
   610     if (!loop_) {
   611         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   612         return;
   613     }
   614 
   615     __ j(OP_CONTINUE, loop_->continue_());
   616 }
   617 
   618 void
   619 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   620 {
   621     HIR *left = eval(node->left());
   622     if (!left)
   623         return;
   624 
   625     HIR *right = eval(node->right());
   626     if (!right)
   627         return;
   628 
   629     // Hrm... yes, for now, let's coerce here.
   630     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   631     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   632         return;
   633     
   634     // Do not coerce here, there's no reason to yet.
   635     if (!left->type()->isArray()) {
   636         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   637         return;
   638     }
   639 
   640     hir_ = new (pool_) HIndex(node,
   641                               ArrayType::cast(left->type())->contained(),
   642                               left,
   643                               right);
   644 }
   645 
   646 void
   647 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   648 {
   649     HLValue *lval = lvalue(node->expression());
   650     if (!lval)
   651         return;
   652 
   653     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   654         assert(false);
   655         return;
   656     }
   657 
   658     HIR *rval;
   659     if (lval->type()->isInt32())
   660         rval = new (pool_) HInteger(node, lval->type(), 1);
   661     else
   662         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   663 
   664     if (node->postfix())
   665         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   666     else
   667         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   668 }
   669 
   670 Type *
   671 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   672 {
   673     Handle<Type> l = left->type();
   674     Handle<Type> r = right->type();
   675 
   676     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   677         // We allow: [float|int32] + [float|int32]
   678         if (l->isFloat() && r->isInt32())
   679             return l;
   680         if (l->isInt32() && r->isFloat())
   681             return r;
   682         if (l->isInt32() && r->isInt32())
   683             return l;
   684     }
   685 
   686     // :TODO: remove
   687     assert(l == r);
   688 
   689     return left->type();
   690 }
   691 
   692 bool
   693 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   694                                  Handle<Type> argGiven,
   695                                  Handle<Type> argActual,
   696                                  CoercionKind kind)
   697 {
   698     if (!argGiven->isArray()) {
   699         cc_.reportError(pos, Message_ExpectedArray);
   700         return false;
   701     }
   702 
   703     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   704     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   705 
   706     if (actual->levels() != given->levels()) {
   707         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   708         return false;
   709     }
   710 
   711     unsigned level = 1;
   712     while (true) {
   713         if (actual->isFixedLength()) {
   714             if (kind == Coerce_Return || kind == Coerce_Assign) {
   715                 if (!given->isFixedLength()) {
   716                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   717                     return false;
   718                 }
   719 
   720                 if (actual->isCharArray()) {
   721                     // String assignment can have a truncated |given|.
   722                     if (given->fixedLength() > actual->fixedLength()) {
   723                         cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   724                         return false;
   725                     }
   726                 } else {
   727                     if (given->fixedLength() != actual->fixedLength()) {
   728                         cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   729                         return false;
   730                     }
   731                 }
   732             }
   733         } else if (given->isFixedLength()) {
   734             // We do not allow assignments in the form:
   735             //  [][] = [][Y]
   736             //
   737             // Otherwise, the following code could break the size guarantees
   738             // of the right-hand side:
   739             //
   740             //  new x[][5];
   741             //  new y[][];
   742             //  new z[3];
   743             //
   744             //
   745             //  y = x;
   746             //  y[0] = z;
   747             //
   748             // Now |x[0]| contains a 3-length array.
   749             if (level > 1) {
   750                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   751                 return false;
   752             }
   753         }
   754 
   755         if (!given->contained()->isArray() || !actual->contained()->isArray())
   756             break;
   757 
   758         given = ArrayType::cast(given->contained());
   759         actual = ArrayType::cast(actual->contained());
   760     }
   761 
   762     // These arrays must contain the same innermost type.
   763     if (given->contained() != actual->contained()) {
   764         cc_.reportError(pos, Message_TypeMismatch,
   765                         GetTypeName(actual->contained()),
   766                         GetTypeName(given->contained()));
   767         return false;
   768     }
   769 
   770     return true;
   771 }
   772 
   773 HIR *
   774 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   775 {
   776     Handle<Type> from = hir->type();
   777 
   778     if (from->isInt32() && to->isFloat())
   779         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
   780     if (from->isInt32() && to->isBool())
   781         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
   782     
   783     if (to->isArray()) {
   784         if (!typeCheckArray(SourcePosition(), from, to, kind))
   785             return NULL;
   786         return hir;
   787     }
   788     
   789     return hir;
   790 }
   791 
   792 void
   793 SemanticAnalysis::set(VariableSymbol *sym)
   794 {
   795     if (sym->scope()->kind() == Scope::GLOBAL) {
   796         __ setglobal(sym);
   797     } else {
   798         assert(sym->storage() == VariableSymbol::Local);
   799         __ setlocal(sym);
   800     }
   801 }
   802 
   803 HIR *
   804 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
   805 {
   806     Local<Type> coercion(zone_, coercionType(token, left, right));
   807     if (!coercion)
   808         return NULL;
   809     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
   810         return NULL;
   811     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
   812         return NULL;
   813     
   814     switch (token) {
   815      case TOK_PLUS:
   816       case TOK_MINUS:
   817       case TOK_STAR:
   818       case TOK_SLASH:
   819       case TOK_PERCENT:
   820       case TOK_AMPERSAND:
   821       case TOK_BITOR:
   822       case TOK_BITXOR:
   823       case TOK_SHR:
   824       case TOK_USHR:
   825       case TOK_SHL:
   826         return new (pool_) HBinary(node, left->type(), token, left, right);
   827 
   828       case TOK_EQUALS:
   829       case TOK_NOTEQUALS:
   830       case TOK_LT:
   831       case TOK_LE:
   832       case TOK_GT:
   833       case TOK_GE:
   834       case TOK_AND:
   835       case TOK_OR:
   836       {
   837         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   838         return new (pool_) HBinary(node, result, token, left, right);
   839       }
   840 
   841       default:
   842         assert(false);
   843         return NULL;
   844     }
   845 }
   846 
   847 static inline TokenKind
   848 ToCompare(Expression *expr)
   849 {
   850     if (expr->isBinaryExpression()) {
   851         BinaryExpression *b = expr->toBinaryExpression();
   852         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
   853             return b->token();
   854     } else if (expr->isUnaryExpression()) {
   855         UnaryExpression *u = expr->toUnaryExpression();
   856         if (u->token() == TOK_NOT)
   857             return TOK_NOT;
   858     }
   859     return TOK_EOF;
   860 }
   861 
   862 void
   863 SemanticAnalysis::visitForTest(Expression *expr,
   864                                Label *trueBranch,
   865                                Label *falseBranch,
   866                                Label *fallthrough)
   867 {
   868     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   869 
   870     TokenKind token = ToCompare(expr);
   871     if (token == TOK_EOF || token == TOK_NOT) {
   872         HIR *hir;
   873         if (token == TOK_EOF)
   874             hir = eval(expr);
   875         else
   876             hir = eval(expr->toUnaryExpression()->expression());
   877         if (!hir)
   878             return;
   879         if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   880             return;
   881 
   882         discharge(hir);
   883 
   884         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
   885         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
   886         
   887         if (fallthrough == falseBranch)
   888             __ j(op, trueBranch);
   889         else
   890             __ j(op, falseBranch);
   891         return;
   892     }
   893 
   894     BinaryExpression *bin = expr->toBinaryExpression();
   895     if (token == TOK_AND || token == TOK_OR) {
   896         assert(false);
   897         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
   898         return;
   899     }
   900 
   901     HIR *left = eval(bin->left());
   902     HIR *right = eval(bin->right());
   903     if (!left || !right)
   904         return;
   905 
   906     HIR *hir = binary(bin, bin->token(), left, right);
   907     if (!hir)
   908         return;
   909     if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
   910         return;
   911 
   912     discharge(hir);
   913     if (fallthrough == trueBranch)
   914         __ j(OP_JF, falseBranch);
   915     else
   916         __ j(OP_JT, trueBranch);
   917 }
   918 
   919 HLValue *
   920 SemanticAnalysis::lvalue(Expression *expr)
   921 {
   922     HIR *hir = eval(expr);
   923     if (!hir)
   924         return NULL;
   925     
   926     if (!hir->isLValue()) {
   927         cc_.reportError(expr->pos(), Message_ExpectedLValue);
   928         return NULL;
   929     }
   930 
   931     return static_cast<HLValue *>(hir);
   932 }
   933 
   934 HIR *
   935 SemanticAnalysis::eval(Expression *expr)
   936 {
   937     assert(!hir_);
   938     expr->accept(this);
   939 
   940     HIR *hir = hir_;
   941     hir_ = NULL;
   942 
   943     return hir;
   944 }
   945 
   946 void
   947 SemanticAnalysis::discharge(HIR *hir)
   948 {
   949     EmitHIR(zone_, emitter_, hir);
   950 }