src/compiler/SemanticAnalysis.cpp
author David Anderson <dvander@alliedmods.net>
Wed Dec 26 17:20:55 2012 -0800 (2012-12-26)
changeset 244 3c57bbf22aa2
parent 241 18f3010a358c
child 245 9371f058625a
permissions -rw-r--r--
Fix clang bustage.
     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     control_(NULL)
    84 {
    85 
    86 }
    87 
    88 void
    89 SemanticAnalysis::analyze()
    90 {
    91     scope_ = unit_->globalScope();
    92 
    93     module_ = Module::New(zone_);
    94 
    95     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    96         Statement *stmt = unit_->tree()->statements()->at(i);
    97         stmt->accept(this);
    98     }
    99 
   100     Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
   101     if (!globals)
   102         return;
   103     module_->setGlobals(globals);
   104 
   105     Local<Code> code(zone_, __ finish());
   106     if (!code)
   107         return;
   108     code->setModule(module_);
   109     module_->setCode(code);
   110 
   111 #ifndef NDEBUG
   112 //    Disassemble(code, stdout);
   113 #endif
   114 
   115     unit_->module_ = module_;
   116 }
   117 
   118 void
   119 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   120 {
   121     FunctionSymbol *sym = stmt->sym();
   122     Local<FunctionType> type(zone_, sym->type());
   123 
   124     assert(scope_->kind() == Scope::GLOBAL);
   125 
   126     if (stmt->token() == TOK_NATIVE) {
   127         // Define the native now.
   128         size_t index;
   129         if (!zone_->nativeTable()->add(stmt->name(), &index))
   130             return;
   131 
   132         Local<Native> native(zone_, Native::New(zone_, type, index));
   133         if (!native)
   134             return;
   135 
   136         __ object(native);
   137         __ setglobal(sym);
   138         __ pop();
   139     }
   140 
   141     // If the function is a forward or native, we don't have to do anything.
   142     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   143         return;
   144 
   145     SemanticAnalysis child(this, type);
   146     Local<Function> funobj(zone_, child.compile(stmt));
   147     if (!funobj)
   148         return;
   149 
   150     __ object(funobj);
   151     __ setglobal(sym);
   152     if (stmt->token() == TOK_PUBLIC)
   153         __ public_();
   154     else
   155         __ pop();
   156 }
   157 
   158 Function *
   159 SemanticAnalysis::compile(FunctionStatement *stmt)
   160 {
   161     __ setFirstLine(stmt->pos().line);
   162 
   163     AutoEnterScope argScope(&scope_, stmt->argScope());
   164 
   165     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   166         Parameter *param = stmt->signature().parameters()->at(i);
   167         param->sym()->allocate(VariableSymbol::Arg, i);
   168     }
   169 
   170     AutoEnterScope varScope(&scope_, stmt->varScope());
   171     ControlStatus status = visitForControl(stmt->body());
   172 
   173     if (!fun_->returnType()->isVoid()) {
   174         // If the function is not void, report if not all paths return a value.
   175         // All other incorrect return cases have been caught already.
   176         if (status.returns() == Returns_Sometimes) {
   177             cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
   178             return NULL;
   179         }
   180 
   181         if (status.returns() == Returns_Never) {
   182             cc_.reportError(stmt->pos(), Message_MissingReturnValue);
   183             return NULL;
   184         }
   185     }
   186 
   187     Local<Code> code(zone_, __ finish());
   188     if (!code)
   189         return NULL;
   190     code->setModule(module_);
   191 
   192     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   193     if (!fun)
   194         return NULL;
   195 
   196 #ifndef NDEBUG
   197 //    Disassemble(code, stdout);
   198 #endif
   199 
   200     return fun;
   201 }
   202 
   203 void 
   204 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   205 {
   206     AutoEnterScope scope(&scope_, node->scope());
   207 
   208     for (size_t i = 0; i < node->statements()->length(); i++) {
   209         Statement *stmt = node->statements()->at(i);
   210         __ note_position(stmt->pos());
   211         stmt->accept(this);
   212         assert(__ stackDepth() == 0);
   213     }
   214 }
   215 
   216 void
   217 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
   218 {
   219 }
   220 
   221 void
   222 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   223 {
   224     // While building HIR, we enter new pool and root scopes, since HIR
   225     // creation is purely temporary.
   226     PoolScope poolScope(zone_->pool());
   227     RootScope rootScope(zone_);
   228 
   229     HIR *hir = eval(node->expression());
   230     if (!hir)
   231         return;
   232 
   233     discharge(hir);
   234     if (!hir->type()->isVoid())
   235         __ pop();
   236 }
   237 
   238 void
   239 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
   240 {
   241     // If both sides terminate in a return, we consider this a return as well.
   242     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
   243         terminate(Returns_Always);
   244         return;
   245     }
   246 
   247     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
   248                           ? Returns_Never
   249                           : Returns_Sometimes;
   250 
   251     if (left.terminates() && right.terminates())
   252         terminate(status);
   253     else
   254         returns(status);
   255 }
   256 
   257 SemanticAnalysis::ControlStatus
   258 SemanticAnalysis::visitForControl(Statement *statement)
   259 {
   260     ControlScope scope(&control_);
   261     statement->accept(this);
   262     return scope.status();
   263 }
   264 
   265 void
   266 SemanticAnalysis::visitIfStatement(IfStatement *node)
   267 {
   268     Label join;
   269 
   270     ControlStatus trueBranch;
   271     ControlStatus falseBranch(false, Returns_Never);
   272 
   273     if (!node->ifFalse()) {
   274         Label success;
   275 
   276         visitForTest(node->condition(), &success, &join, &success);
   277         __ bind(&success);
   278         trueBranch = visitForControl(node->ifTrue());
   279     } else {
   280         Label success, next;
   281 
   282         visitForTest(node->condition(), &success, &next, &success);
   283         __ bind(&success);
   284         trueBranch = visitForControl(node->ifTrue());
   285         __ jump(&join);
   286         __ bind(&next);
   287         falseBranch = visitForControl(node->ifFalse());
   288     }
   289 
   290     __ bind(&join);
   291 
   292     control_->merge(trueBranch, falseBranch);
   293 }
   294 
   295 void
   296 SemanticAnalysis::requireLifoStack()
   297 {
   298     if (!loop_)
   299         return;
   300 
   301     loop_->setUsesLifoStack();
   302 }
   303 
   304 SemanticAnalysis::ControlStatus
   305 SemanticAnalysis::visitLoopBody(Statement *stmt)
   306 {
   307     // We always mark off a loop body, so on each edge, we can balance the
   308     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   309     // stack ahead of time. If we turn out to never need the LIFO stack, we
   310     // mark it as unnecessary. (The interpreter can't really make use of this,
   311     // but the JIT can).
   312     //
   313     // Note that balancing the LIFO stack isn't even necessary, so this
   314     // feature may be removed. All this mechanism does is mitigate the
   315     // possibility that a long-running loop will overflow the LIFO region
   316     // and therefore start requiring nursery allocations.
   317     int pos = __ enterloop();
   318     ControlStatus status = visitForControl(stmt);
   319     __ leaveloop();
   320 
   321     if (loop_->usesLifoStack())
   322         __ setLoopUsesLifoStack(pos);
   323 
   324     return status;
   325 }
   326 
   327 void
   328 SemanticAnalysis::visitForStatement(ForStatement *node)
   329 {
   330     AutoEnterScope scope(&scope_, node->scope());
   331     PoolScope poolScope(zone_->pool());
   332     RootScope rootScope(zone_);
   333 
   334     Label join, update;
   335     LoopScope loop(scope_, &join, &update, &loop_);
   336 
   337     if (node->initialization())
   338         node->initialization()->accept(this);
   339 
   340     Label header, test;
   341     if (node->condition())
   342         __ jump(&test);
   343 
   344     __ bind(&header);
   345     ControlStatus status = visitLoopBody(node->body());
   346 
   347     __ bind(&update);
   348     if (node->update())
   349         node->update()->accept(this);
   350 
   351     if (node->condition()) {
   352         __ bind(&test);
   353         visitForTest(node->condition(), &header, &join, &join);
   354     } else {
   355         __ jump(&header);
   356     }
   357 
   358     __ bind(&join);
   359     
   360     // If there was a condition, we treat this like a while loop. Otherwise,
   361     // the join point is only reachable if the loop contains a break. The
   362     // termination status doesn't tell us anything yet.
   363     if (node->condition() || loop.breaks())
   364         control_->merge(status, ControlStatus(false, Returns_Never));
   365     else
   366         control_->terminate(status.returns());
   367 
   368     assert(__ stackDepth() == 0);
   369 }
   370 
   371 void
   372 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   373 {
   374     PoolScope poolScope(zone_->pool());
   375     RootScope rootScope(zone_);
   376 
   377     Label header, join;
   378 
   379     __ bind(&header);
   380 
   381     ControlStatus status;
   382 
   383     LoopScope loop(scope_, &join, &header, &loop_);
   384     if (node->token() == TOK_WHILE) {
   385         Label body;
   386         visitForTest(node->condition(), &body, &join, &body);
   387         status = visitLoopBody(node->body());
   388         __ jump(&header);
   389     } else {
   390         status = visitLoopBody(node->body());
   391         visitForTest(node->condition(), &header, &join, &join);
   392     }
   393 
   394     __ bind(&join);
   395 
   396     // Detect loops that will always have a fork in the contro-flow graph.
   397     // This will be a |while| loop, or a |do-while| loop whose body does
   398     // not terminate. For now, we treat these as an |if| regardless of the
   399     // direction the branch can take. That means the control-flow is always
   400     // conditional.
   401     if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
   402         control_->merge(status, ControlStatus(false, Returns_Never));
   403     } else {
   404         // At this point, we've got a do-while loop with a |return| or
   405         // |continue|, meaning that the rest of the block is unreachable.
   406         control_->terminate(status.returns());
   407     }
   408 
   409     assert(__ stackDepth() == 0);
   410 }
   411 
   412 static inline Heap::Tenure
   413 InferTenure(Symbol *sym)
   414 {
   415     if (sym->scope()->kind() == Scope::GLOBAL)
   416         return Heap::Tenure_Old;
   417 
   418     // SP2's array semantics allow any array kind to escape, so we must use
   419     // the normal heap. (Hopefully escape analysis can ease this pain later).
   420     if (sym->type()->isArray())
   421         return Heap::Tenure_Default;
   422 
   423     return Heap::Tenure_Default;
   424 }
   425 
   426 void
   427 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   428 {
   429     PoolScope poolScope(zone_->pool());
   430     RootScope rootScope(zone_);
   431 
   432     Local<Type> type(zone_, node->sym()->type());
   433 
   434     if (node->sym()->type()->isVoid()) {
   435         cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
   436         return;
   437     }
   438 
   439     if (node->initialization()) {
   440         HIR *hir = NULL;
   441 
   442         if ((hir = eval(node->initialization())) == NULL)
   443             return;
   444         if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
   445             return;
   446 
   447         discharge(hir);
   448     } else {
   449         if (type->isInt32() || type->isEnum() ||
   450             type->isChar() || type->isBool())
   451         {
   452             __ int_(0);
   453         } else if (type->isFloat()) {
   454             __ float_(0);
   455         } else if (type->isArray()) {
   456             Local<ArrayType> atype(zone_, ArrayType::cast(type));
   457             Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, atype));
   458             if (!map)
   459                 return;
   460 
   461             if (atype->isFixedLength()) {
   462                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   463             } else if (node->dims()->at(0)) {
   464                 // This may not be true if we allow typedefing, so :TODO:
   465                 // figure out proper semantics.
   466                 assert(node->dims()->length() == atype->levels());
   467 
   468                 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   469                 for (size_t i = 0; i < node->dims()->length(); i++) {
   470                     Expression *expr = node->dims()->at(i);
   471                     if (expr) {
   472                         HIR *hir = eval(expr);
   473                         if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
   474                             return;
   475                         discharge(hir);
   476                     } else {
   477                         __ int_(0);
   478                     }
   479                 }
   480                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   481             } else {
   482                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   483             }
   484         } else {
   485             assert(false);
   486         }
   487     }
   488 
   489     if (node->sym()->scope()->kind() != Scope::GLOBAL) {
   490         if (!__ allocate(node->sym()))
   491             return;
   492     }
   493 
   494     set(node->sym());
   495     __ pop();
   496 }
   497 
   498 void
   499 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   500 {
   501     control_->returns(Returns_Always);
   502 
   503     if (!node->expression()) {
   504         if (!fun_->returnType()->isVoid()) {
   505             cc_.reportError(node->pos(), Message_MissingReturnValue);
   506             return;
   507         }
   508 
   509         __ returnvoid();
   510         return;
   511     }
   512 
   513     if (fun_->returnType()->isVoid()) {
   514         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   515         return;
   516     }
   517 
   518     PoolScope poolScope(zone_->pool());
   519     RootScope rootScope(zone_);
   520 
   521     HIR *hir = eval(node->expression());
   522     if (!hir)
   523         return;
   524 
   525     Local<Type> returnType(zone_, fun_->returnType());
   526     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   527         return;
   528 
   529     discharge(hir);
   530 
   531     if (hir->type()->isVoid())
   532         __ returnvoid();
   533     else
   534         __ return_();
   535 }
   536 
   537 void
   538 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   539 {
   540     HIR *left = eval(node->left());
   541     HIR *right = eval(node->right());
   542     if (!left || !right)
   543         return;
   544 
   545     hir_ = binary(node, node->token(), left, right);
   546 }
   547 
   548 bool
   549 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   550 {
   551     if (type->parameters()->length() == actual)
   552         return true;
   553 
   554     if (actual > type->parameters()->length()) {
   555         if (!type->isNative() || !type->isNativeVariadic())
   556             return false;
   557         return true;
   558     }
   559 
   560     if (!type->defaults())
   561         return false;
   562 
   563     // Missing arguments. See if there's a default argument for each missing
   564     // actual.
   565     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   566         if (!type->defaults()->at(i))
   567             return false;
   568     }
   569 
   570     return true;
   571 }
   572 
   573 void
   574 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   575 {
   576     Symbol *sym = proxy->sym();
   577 
   578     switch (sym->kind()) {
   579       case Symbol::kConstant:
   580       {
   581         ConstantSymbol *val = sym->toConstant();
   582         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   583         break;
   584       }
   585       
   586       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   587       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   588       // kFunction is only used for global functions (and use const vars for
   589       // local functions).
   590       case Symbol::kFunction:
   591       case Symbol::kVariable:
   592       {
   593         Scope *in = sym->scope();
   594         switch (in->kind()) {
   595           case Scope::GLOBAL:
   596             hir_ = new (pool_) HGlobal(proxy, sym);
   597             break;
   598 
   599           case Scope::FUNCTION:
   600           {
   601             VariableSymbol *var = sym->toVariable();
   602             assert(var->storage() == VariableSymbol::Arg);
   603             hir_ = new (pool_) HLocal(proxy, var);
   604             break;
   605           }
   606 
   607           default:
   608           {
   609             VariableSymbol *var = sym->toVariable();
   610             assert(in->kind() == Scope::BLOCK);
   611             assert(var->storage() == VariableSymbol::Local);
   612             hir_ = new (pool_) HLocal(proxy, var);
   613             break;
   614           }
   615         }
   616         break;
   617       }
   618 
   619       default:
   620         // :TODO:
   621         assert(false);
   622     }
   623 }
   624 
   625 void
   626 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   627 {
   628     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   629     hir_ = new (pool_) HInteger(lit, type, lit->value());
   630 }
   631 
   632 void
   633 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   634 {
   635     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   636     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   637 }
   638 
   639 void
   640 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
   641 {
   642     Type *type = zone_->types()->getString();
   643     hir_ = new (pool_) HString(node, type, node->string());
   644 }
   645 
   646 void
   647 SemanticAnalysis::visitCallExpression(CallExpression *node)
   648 {
   649     HIR *callee = eval(node->callee());
   650     if (!callee)
   651         return;
   652 
   653     if (!callee->type()->isFunction()) {
   654         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   655         return;
   656     }
   657 
   658     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   659     
   660     if (!checkArgumentCount(fun, node->arguments()->length())) {
   661         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   662         return;
   663     }
   664 
   665     if (fun->isForward()) {
   666         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   667         return;
   668     }
   669 
   670     HIRList *args = new (pool_) HIRList;
   671     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   672         Expression *expression = node->arguments()->at(i);
   673         HIR *arg = eval(expression);
   674         if (!arg)
   675             return;
   676 
   677         Handle<Type> given = arg->type();
   678         
   679         bool mustComputeReference;
   680         if (i >= fun->parameters()->length()) {
   681             // Special handling for natives. Arguments past the formal must
   682             // always have references computed. However, arrays are already
   683             // references for natives.
   684             assert(fun->isNative() && fun->isNativeVariadic());
   685             mustComputeReference = !given->isReference() &&
   686                                    !given->isArray();
   687         } else {
   688             Local<Type> actual(zone_, fun->parameterAt(i));
   689 
   690             if (expression->isIndexExpression()) {
   691                 // Temporarily disabled.
   692                 assert(!actual->isArray());
   693                 if (actual->isReference()) {
   694                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   695                     return;
   696                 }
   697             }
   698 
   699             if (actual->isReference()) {
   700                 // If the actual is a reference, the coercion rules are much
   701                 // stricter; the contained types must be identical.
   702                 // :TODO: make this not an assert
   703                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   704             } else {
   705                 // When we start overloading, coercion will have to happen later.
   706                 arg = coerce(arg, actual, Coerce_Arg);
   707                 if (!arg)
   708                     return;
   709             }
   710 
   711             mustComputeReference = actual->isReference() && !given->isReference();
   712         }
   713 
   714         if (mustComputeReference) {
   715             // Refs always use the LIFO stack if they can.
   716             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   717             requireLifoStack();
   718         }
   719 
   720         if (!args->append(arg))
   721             return;
   722     }
   723 
   724     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   725 }
   726 
   727 void
   728 SemanticAnalysis::visitAssignment(Assignment *node)
   729 {
   730     HLValue *lval = lvalue(node->lvalue());
   731     if (!lval)
   732         return;
   733 
   734     if (lval->type()->quals() & TypeQual_Const) {
   735         cc_.reportError(node->pos(), Message_CannotModifyConst);
   736         return;
   737     }
   738 
   739     HIR *hir = eval(node->expression());
   740     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   741         return;
   742 
   743     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   744 }
   745 
   746 void
   747 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   748 {
   749     if (!loop_) {
   750         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   751         return;
   752     }
   753 
   754     loop_->setBreaks();
   755     __ j(OP_BREAK, loop_->break_());
   756 }
   757 
   758 void
   759 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   760 {
   761     if (!loop_) {
   762         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   763         return;
   764     }
   765 
   766     __ j(OP_CONTINUE, loop_->continue_());
   767 }
   768 
   769 void
   770 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   771 {
   772     HIR *left = eval(node->left());
   773     if (!left)
   774         return;
   775 
   776     HIR *right = eval(node->right());
   777     if (!right)
   778         return;
   779 
   780     // Hrm... yes, for now, let's coerce here.
   781     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   782     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   783         return;
   784     
   785     // Do not coerce here, there's no reason to yet.
   786     if (!left->type()->isArray()) {
   787         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   788         return;
   789     }
   790 
   791     hir_ = new (pool_) HIndex(node,
   792                               ArrayType::cast(left->type())->contained(),
   793                               left,
   794                               right);
   795 }
   796 
   797 void
   798 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   799 {
   800     HLValue *lval = lvalue(node->expression());
   801     if (!lval)
   802         return;
   803 
   804     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   805         assert(false);
   806         return;
   807     }
   808 
   809     HIR *rval;
   810     if (lval->type()->isInt32())
   811         rval = new (pool_) HInteger(node, lval->type(), 1);
   812     else
   813         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   814 
   815     if (node->postfix())
   816         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   817     else
   818         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   819 }
   820 
   821 Type *
   822 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   823 {
   824     Handle<Type> l = left->type();
   825     Handle<Type> r = right->type();
   826 
   827     if (token >= TOK_PLUS && token <= TOK_SLASH) {
   828         // We allow: [float|int32] + [float|int32]
   829         if (l->isFloat() && r->isInt32())
   830             return l;
   831         if (l->isInt32() && r->isFloat())
   832             return r;
   833         if (l->isInt32() && r->isInt32())
   834             return l;
   835     }
   836 
   837     // :TODO: remove
   838     assert(l == r);
   839 
   840     return left->type();
   841 }
   842 
   843 HIR *
   844 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   845                                  HIR *from,
   846                                  Handle<ArrayType> argActual,
   847                                  CoercionKind kind)
   848 {
   849     Local<Type> argGiven(zone_, from->type());
   850 
   851     // Special case: if we receive a string literal, and this is a char array,
   852     // we allow a coercion.
   853     if (from->isString() &&
   854         argGiven->isString() &&
   855         argActual->isArray() &&
   856         ArrayType::cast(argActual)->isCharArray())
   857     {
   858         HString *hir = from->toString();
   859         Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   860 
   861         if (actual->isFixedLength()) {
   862             if (hir->string()->length() + 1 > actual->fixedLength()) {
   863                 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   864                 return NULL;
   865             }
   866         }
   867 
   868         // Transform the string literal into an array literal. We give it the
   869         // type of the left-hand side. The constness of the destination type
   870         // will determine whether HArray duplicates it or not.
   871         Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, actual));
   872         if (!map)
   873             return NULL;
   874 
   875         Local<Array> array(zone_);
   876         array = Array::NewString(zone_,
   877                                  map,
   878                                  hir->string()->chars(),
   879                                  hir->string()->length(),
   880                                  Heap::Tenure_Old);
   881         if (!array)
   882             return NULL;
   883 
   884         // Since we're creating a canonical copy of the char array, we have to
   885         // be careful that it doesn't get mutated. There are two cases where
   886         // we know it can't be mutated, and therefore don't need to specify
   887         // that it be cloned after pushing it onto the stack.
   888         //
   889         //  (1) The array type is const.
   890         //  (2) The array type is fixed-length, and the coercion is for
   891         //      assignment, meaning it will be immediately copied.
   892         //
   893         // We treat declaration separately from assignment, since for
   894         // declaration we can just immediately use the cloned version.
   895         bool shouldDuplicate = true;
   896         if ((actual->quals() & TypeQual_Const) ||
   897             (actual->isFixedLength() && kind == Coerce_Assign))
   898         {
   899             shouldDuplicate = false;
   900         }
   901 
   902         return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
   903     }
   904 
   905     if (!argGiven->isArray()) {
   906         cc_.reportError(pos, Message_ExpectedArray);
   907         return NULL;
   908     }
   909 
   910     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   911     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
   912 
   913     if (actual->levels() != given->levels()) {
   914         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
   915         return NULL;
   916     }
   917 
   918     unsigned level = 1;
   919     while (true) {
   920         if (actual->isFixedLength()) {
   921             if (!given->isFixedLength()) {
   922                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   923                 return NULL;
   924             }
   925 
   926             if (actual->isCharArray()) {
   927                 // String assignment can have a truncated |given|.
   928                 if (given->fixedLength() > actual->fixedLength()) {
   929                     cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   930                     return NULL;
   931                 }
   932             } else {
   933                 if (given->fixedLength() != actual->fixedLength()) {
   934                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   935                     return NULL;
   936                 }
   937             }
   938         } else if (given->isFixedLength()) {
   939             // We do not allow assignments in the form:
   940             //  [][] = [][Y]
   941             //
   942             // Otherwise, the following code could break the size guarantees
   943             // of the right-hand side:
   944             //
   945             //  new x[][5];
   946             //  new y[][];
   947             //  new z[3];
   948             //
   949             //
   950             //  y = x;
   951             //  y[0] = z;
   952             //
   953             // Now |x[0]| contains a 3-length array.
   954             if (level > 1) {
   955                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
   956                 return NULL;
   957             }
   958         }
   959 
   960         if (!given->contained()->isArray() || !actual->contained()->isArray())
   961             break;
   962 
   963         given = ArrayType::cast(given->contained());
   964         actual = ArrayType::cast(actual->contained());
   965     }
   966 
   967     bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
   968     bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
   969 
   970     // These arrays must contain the same innermost type.
   971     if (given->contained()->unqualified() != actual->contained()->unqualified() ||
   972         (givenConst && !actualConst))
   973     {
   974         char aname[255];
   975         char gname[255];
   976         cc_.reportError(pos, Message_TypeMismatch,
   977                         GetTypeName(argActual, aname, sizeof(aname)),
   978                         GetTypeName(argGiven, gname, sizeof(gname)));
   979         return NULL;
   980     }
   981 
   982     return from;
   983 }
   984 
   985 HIR *
   986 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
   987 {
   988     char fname[255];
   989     char tname[255];
   990     cc_.reportError(pos, Message_InvalidCoercion,
   991                     GetTypeName(from, fname, sizeof(fname)),
   992                     GetTypeName(to, tname, sizeof(tname)));
   993     return NULL;
   994 }
   995 
   996 HIR *
   997 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
   998 {
   999     Local<Type> from(zone_, hir->type());
  1000 
  1001     if (from->isInt32() && to->isFloat())
  1002         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
  1003     if (from->isInt32() && to->isBool())
  1004         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
  1005 
  1006     if (to->isEnum() && *from != to)
  1007         return typeFailure(hir->node()->pos(), from, to);
  1008     
  1009     if (to->isArray()) {
  1010         Local<ArrayType> atype(zone_, ArrayType::cast(to));
  1011         return typeCheckArray(hir->node()->pos(), hir, atype, kind);
  1012     }
  1013     
  1014     return hir;
  1015 }
  1016 
  1017 void
  1018 SemanticAnalysis::set(VariableSymbol *sym)
  1019 {
  1020     if (sym->scope()->kind() == Scope::GLOBAL) {
  1021         __ setglobal(sym);
  1022     } else {
  1023         assert(sym->storage() == VariableSymbol::Local);
  1024         __ setlocal(sym);
  1025     }
  1026 }
  1027 
  1028 HIR *
  1029 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
  1030 {
  1031     Local<Type> coercion(zone_, coercionType(token, left, right));
  1032     if (!coercion)
  1033         return NULL;
  1034     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
  1035         return NULL;
  1036     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
  1037         return NULL;
  1038     
  1039     switch (token) {
  1040      case TOK_PLUS:
  1041       case TOK_MINUS:
  1042       case TOK_STAR:
  1043       case TOK_SLASH:
  1044       case TOK_PERCENT:
  1045       case TOK_AMPERSAND:
  1046       case TOK_BITOR:
  1047       case TOK_BITXOR:
  1048       case TOK_SHR:
  1049       case TOK_USHR:
  1050       case TOK_SHL:
  1051         return new (pool_) HBinary(node, left->type(), token, left, right);
  1052 
  1053       case TOK_EQUALS:
  1054       case TOK_NOTEQUALS:
  1055       case TOK_LT:
  1056       case TOK_LE:
  1057       case TOK_GT:
  1058       case TOK_GE:
  1059       case TOK_AND:
  1060       case TOK_OR:
  1061       {
  1062         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1063         return new (pool_) HBinary(node, result, token, left, right);
  1064       }
  1065 
  1066       default:
  1067         assert(false);
  1068         return NULL;
  1069     }
  1070 }
  1071 
  1072 static inline TokenKind
  1073 ToCompare(Expression *expr)
  1074 {
  1075     if (expr->isBinaryExpression()) {
  1076         BinaryExpression *b = expr->toBinaryExpression();
  1077         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
  1078             return b->token();
  1079     } else if (expr->isUnaryExpression()) {
  1080         UnaryExpression *u = expr->toUnaryExpression();
  1081         if (u->token() == TOK_NOT)
  1082             return TOK_NOT;
  1083     }
  1084     return TOK_EOF;
  1085 }
  1086 
  1087 void
  1088 SemanticAnalysis::visitForTest(Expression *expr,
  1089                                Label *trueBranch,
  1090                                Label *falseBranch,
  1091                                Label *fallthrough)
  1092 {
  1093     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1094 
  1095     TokenKind token = ToCompare(expr);
  1096     if (token == TOK_EOF || token == TOK_NOT) {
  1097         HIR *hir;
  1098         if (token == TOK_EOF)
  1099             hir = eval(expr);
  1100         else
  1101             hir = eval(expr->toUnaryExpression()->expression());
  1102         if (!hir)
  1103             return;
  1104         if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1105             return;
  1106 
  1107         discharge(hir);
  1108 
  1109         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1110         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1111         
  1112         if (fallthrough == falseBranch)
  1113             __ j(op, trueBranch);
  1114         else
  1115             __ j(op, falseBranch);
  1116         return;
  1117     }
  1118 
  1119     BinaryExpression *bin = expr->toBinaryExpression();
  1120     if (token == TOK_AND || token == TOK_OR) {
  1121         assert(false);
  1122         //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
  1123         return;
  1124     }
  1125 
  1126     HIR *left = eval(bin->left());
  1127     HIR *right = eval(bin->right());
  1128     if (!left || !right)
  1129         return;
  1130 
  1131     HIR *hir = binary(bin, bin->token(), left, right);
  1132     if (!hir)
  1133         return;
  1134     if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1135         return;
  1136 
  1137     discharge(hir);
  1138     if (fallthrough == trueBranch)
  1139         __ j(OP_JF, falseBranch);
  1140     else
  1141         __ j(OP_JT, trueBranch);
  1142 }
  1143 
  1144 HLValue *
  1145 SemanticAnalysis::lvalue(Expression *expr)
  1146 {
  1147     HIR *hir = eval(expr);
  1148     if (!hir)
  1149         return NULL;
  1150     
  1151     if (!hir->isLValue()) {
  1152         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1153         return NULL;
  1154     }
  1155 
  1156     return static_cast<HLValue *>(hir);
  1157 }
  1158 
  1159 HIR *
  1160 SemanticAnalysis::eval(Expression *expr)
  1161 {
  1162     assert(!hir_);
  1163     expr->accept(this);
  1164 
  1165     HIR *hir = hir_;
  1166     hir_ = NULL;
  1167 
  1168     return hir;
  1169 }
  1170 
  1171 void
  1172 SemanticAnalysis::discharge(HIR *hir)
  1173 {
  1174     EmitHIR(zone_, emitter_, hir);
  1175 }