src/compiler/SemanticAnalysis.cpp
author Asher Baker <asherkin@gmail.com>
Mon Jun 10 00:46:29 2013 +0100 (2013-06-10)
changeset 262 c4b1341297e5
parent 261 219b49bf4a03
child 263 ba85a47ee414
permissions -rw-r--r--
Fix warnings when building with clang.
     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     loop_(NULL)
    67 {
    68 }
    69 
    70 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
    71   : zone_(parent->zone_),
    72     pool_(parent->pool_),
    73     cc_(parent->cc_),
    74     unit_(parent->unit_),
    75     hir_(NULL),
    76     scope_(parent->scope_),
    77     fun_(fun),
    78     loop_(NULL),
    79     control_(NULL)
    80 {
    81 
    82 }
    83 
    84 void
    85 SemanticAnalysis::analyze()
    86 {
    87     scope_ = unit_->globalScope();
    88 
    89     for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
    90         Statement *stmt = unit_->tree()->statements()->at(i);
    91         stmt->accept(this);
    92     }
    93 
    94     Local<Code> code(zone_, __ finish());
    95     if (!code)
    96         return;
    97     code->setModule(unit_->module());
    98     unit_->module()->setCode(code);
    99 
   100 #ifndef NDEBUG
   101 //    Disassemble(code, stdout);
   102 #endif
   103 }
   104 
   105 void
   106 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
   107 {
   108     FunctionSymbol *sym = stmt->sym();
   109     Local<FunctionType> type(zone_, sym->type());
   110 
   111     assert(scope_->kind() == Scope::GLOBAL);
   112 
   113     if (stmt->token() == TOK_NATIVE) {
   114         // Define the native now.
   115         size_t index;
   116         if (!zone_->nativeTable()->add(stmt->name(), &index))
   117             return;
   118 
   119         Local<Native> native(zone_, Native::New(zone_, type, index));
   120         if (!native)
   121             return;
   122 
   123         __ object(native);
   124         __ setglobal(sym);
   125         __ pop();
   126     }
   127 
   128     // If the function is a forward or native, we don't have to do anything.
   129     if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
   130         return;
   131 
   132     SemanticAnalysis child(this, type);
   133     Local<Function> funobj(zone_, child.compile(stmt));
   134     if (!funobj)
   135         return;
   136 
   137     __ object(funobj);
   138     __ setglobal(sym);
   139     if (stmt->token() == TOK_PUBLIC)
   140         __ public_();
   141     else
   142         __ pop();
   143 }
   144 
   145 Function *
   146 SemanticAnalysis::compile(FunctionStatement *stmt)
   147 {
   148     __ setFirstLine(stmt->pos().line);
   149 
   150     AutoEnterScope argScope(&scope_, stmt->argScope());
   151 
   152     for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
   153         Parameter *param = stmt->signature().parameters()->at(i);
   154         param->sym()->allocate(VariableSymbol::Arg, i);
   155     }
   156 
   157     AutoEnterScope varScope(&scope_, stmt->varScope());
   158     ControlStatus status = visitForControl(stmt->body());
   159 
   160     if (!fun_->returnType()->isVoid()) {
   161         // If the function is not void, report if not all paths return a value.
   162         // All other incorrect return cases have been caught already.
   163         if (status.returns() == Returns_Sometimes) {
   164             cc_.reportError(stmt->pos(), Message_NotAllPathsReturnValue);
   165             return NULL;
   166         }
   167 
   168         if (status.returns() == Returns_Never) {
   169             cc_.reportError(stmt->pos(), Message_MissingReturnValue);
   170             return NULL;
   171         }
   172     }
   173 
   174     Local<Code> code(zone_, __ finish());
   175     if (!code)
   176         return NULL;
   177     code->setModule(unit_->module());
   178 
   179     Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
   180     if (!fun)
   181         return NULL;
   182 
   183 #ifndef NDEBUG
   184 //    Disassemble(code, stdout);
   185 #endif
   186 
   187     return fun;
   188 }
   189 
   190 void 
   191 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
   192 {
   193     AutoEnterScope scope(&scope_, node->scope());
   194 
   195     for (size_t i = 0; i < node->statements()->length(); i++) {
   196         Statement *stmt = node->statements()->at(i);
   197         __ note_position(stmt->pos());
   198         stmt->accept(this);
   199         assert(__ stackDepth() == 0);
   200     }
   201 }
   202 
   203 void
   204 SemanticAnalysis::visitEnumStatement(EnumStatement *node)
   205 {
   206 }
   207 
   208 void
   209 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
   210 {
   211     // While building HIR, we enter new pool and root scopes, since HIR
   212     // creation is purely temporary.
   213     PoolScope poolScope(zone_->pool());
   214     RootScope rootScope(zone_);
   215 
   216     HIR *hir = eval(node->expression());
   217     if (!hir)
   218         return;
   219 
   220     discharge(hir);
   221     if (!hir->type()->isVoid())
   222         __ pop();
   223 }
   224 
   225 void
   226 SemanticAnalysis::ControlScope::merge(const ControlStatus &left, const ControlStatus &right)
   227 {
   228     // If both sides terminate in a return, we consider this a return as well.
   229     if (left.returns() == Returns_Always && right.returns() == Returns_Always) {
   230         terminate(Returns_Always);
   231         return;
   232     }
   233 
   234     ReturnStatus status = (left.returns() == Returns_Never && right.returns() == Returns_Never)
   235                           ? Returns_Never
   236                           : Returns_Sometimes;
   237 
   238     if (left.terminates() && right.terminates())
   239         terminate(status);
   240     else
   241         returns(status);
   242 }
   243 
   244 SemanticAnalysis::ControlStatus
   245 SemanticAnalysis::visitForControl(Statement *statement)
   246 {
   247     ControlScope scope(&control_);
   248     statement->accept(this);
   249     return scope.status();
   250 }
   251 
   252 void
   253 SemanticAnalysis::visitIfStatement(IfStatement *node)
   254 {
   255     Label join;
   256 
   257     ControlStatus trueBranch;
   258     ControlStatus falseBranch(false, Returns_Never);
   259 
   260     if (!node->ifFalse()) {
   261         Label success;
   262 
   263         visitForTest(node->condition(), &success, &join, &success);
   264         __ bind(&success);
   265         trueBranch = visitForControl(node->ifTrue());
   266     } else {
   267         Label success, next;
   268 
   269         visitForTest(node->condition(), &success, &next, &success);
   270         __ bind(&success);
   271         trueBranch = visitForControl(node->ifTrue());
   272         __ jump(&join);
   273         __ bind(&next);
   274         falseBranch = visitForControl(node->ifFalse());
   275     }
   276 
   277     __ bind(&join);
   278 
   279     control_->merge(trueBranch, falseBranch);
   280 }
   281 
   282 void
   283 SemanticAnalysis::requireLifoStack()
   284 {
   285     if (!loop_)
   286         return;
   287 
   288     loop_->setUsesLifoStack();
   289 }
   290 
   291 SemanticAnalysis::ControlStatus
   292 SemanticAnalysis::visitLoopBody(Statement *stmt)
   293 {
   294     // We always mark off a loop body, so on each edge, we can balance the
   295     // LIFO stack. Right now, we don't have the ability to budget the LIFO
   296     // stack ahead of time. If we turn out to never need the LIFO stack, we
   297     // mark it as unnecessary. (The interpreter can't really make use of this,
   298     // but the JIT can).
   299     //
   300     // Note that balancing the LIFO stack isn't even necessary, so this
   301     // feature may be removed. All this mechanism does is mitigate the
   302     // possibility that a long-running loop will overflow the LIFO region
   303     // and therefore start requiring nursery allocations.
   304     int pos = __ enterloop();
   305     ControlStatus status = visitForControl(stmt);
   306     __ leaveloop();
   307 
   308     if (loop_->usesLifoStack())
   309         __ setLoopUsesLifoStack(pos);
   310 
   311     return status;
   312 }
   313 
   314 void
   315 SemanticAnalysis::visitForStatement(ForStatement *node)
   316 {
   317     AutoEnterScope scope(&scope_, node->scope());
   318     PoolScope poolScope(zone_->pool());
   319     RootScope rootScope(zone_);
   320 
   321     Label join, update;
   322     LoopScope loop(scope_, &join, &update, &loop_);
   323 
   324     if (node->initialization())
   325         node->initialization()->accept(this);
   326 
   327     Label header, test;
   328     if (node->condition())
   329         __ jump(&test);
   330 
   331     __ bind(&header);
   332     ControlStatus status = visitLoopBody(node->body());
   333 
   334     __ bind(&update);
   335     if (node->update())
   336         node->update()->accept(this);
   337 
   338     if (node->condition()) {
   339         __ bind(&test);
   340         visitForTest(node->condition(), &header, &join, &join);
   341     } else {
   342         __ jump(&header);
   343     }
   344 
   345     __ bind(&join);
   346     
   347     // If there was a condition, we treat this like a while loop. Otherwise,
   348     // the join point is only reachable if the loop contains a break. The
   349     // termination status doesn't tell us anything yet.
   350     if (node->condition() || loop.breaks())
   351         control_->merge(status, ControlStatus(false, Returns_Never));
   352     else
   353         control_->terminate(status.returns());
   354 
   355     assert(__ stackDepth() == 0);
   356 }
   357 
   358 void
   359 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
   360 {
   361     PoolScope poolScope(zone_->pool());
   362     RootScope rootScope(zone_);
   363 
   364     Label header, join;
   365 
   366     __ bind(&header);
   367 
   368     ControlStatus status;
   369 
   370     LoopScope loop(scope_, &join, &header, &loop_);
   371     if (node->token() == TOK_WHILE) {
   372         Label body;
   373         visitForTest(node->condition(), &body, &join, &body);
   374         status = visitLoopBody(node->body());
   375         __ jump(&header);
   376     } else {
   377         status = visitLoopBody(node->body());
   378         visitForTest(node->condition(), &header, &join, &join);
   379     }
   380 
   381     __ bind(&join);
   382 
   383     // Detect loops that will always have a fork in the contro-flow graph.
   384     // This will be a |while| loop, or a |do-while| loop whose body does
   385     // not terminate. For now, we treat these as an |if| regardless of the
   386     // direction the branch can take. That means the control-flow is always
   387     // conditional.
   388     if (node->token() == TOK_WHILE || status.terminates() || loop.breaks()) {
   389         control_->merge(status, ControlStatus(false, Returns_Never));
   390     } else {
   391         // At this point, we've got a do-while loop with a |return| or
   392         // |continue|, meaning that the rest of the block is unreachable.
   393         control_->terminate(status.returns());
   394     }
   395 
   396     assert(__ stackDepth() == 0);
   397 }
   398 
   399 static inline Heap::Tenure
   400 InferTenure(Symbol *sym)
   401 {
   402     if (sym->scope()->kind() == Scope::GLOBAL)
   403         return Heap::Tenure_Old;
   404 
   405     // SP2's array semantics allow any array kind to escape, so we must use
   406     // the normal heap. (Hopefully escape analysis can ease this pain later).
   407     if (sym->type()->isArray())
   408         return Heap::Tenure_Default;
   409 
   410     return Heap::Tenure_Default;
   411 }
   412 
   413 void
   414 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
   415 {
   416     PoolScope poolScope(zone_->pool());
   417     RootScope rootScope(zone_);
   418 
   419     Local<Type> type(zone_, node->sym()->type());
   420 
   421     if (node->sym()->type()->isVoid()) {
   422         cc_.reportError(node->type()->pos(), Message_CannotDeclareVoid);
   423         return;
   424     }
   425 
   426     if (node->initialization()) {
   427         HIR *hir = NULL;
   428 
   429         if ((hir = eval(node->initialization())) == NULL)
   430             return;
   431         if ((hir = coerce(hir, type, Coerce_Decl)) == NULL)
   432             return;
   433 
   434         discharge(hir);
   435     } else {
   436         if (type->isInt32() || type->isEnum() ||
   437             type->isChar() || type->isBool())
   438         {
   439             __ int_(0);
   440         } else if (type->isFloat()) {
   441             __ float_(0);
   442         } else if (type->isArray()) {
   443             Local<ArrayType> atype(zone_, ArrayType::cast(type));
   444             Local<ArrayMap> map(zone_, atype->newMap());
   445             if (!map)
   446                 return;
   447 
   448             if (atype->isFixedLength()) {
   449                 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
   450             } else if (node->dims()->at(0)) {
   451                 // This may not be true if we allow typedefing, so :TODO:
   452                 // figure out proper semantics.
   453                 assert(node->dims()->length() == atype->levels());
   454 
   455                 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   456                 for (size_t i = 0; i < node->dims()->length(); i++) {
   457                     Expression *expr = node->dims()->at(i);
   458                     if (expr) {
   459                         HIR *hir = eval(expr);
   460                         if (!hir || ((hir = coerce(hir, i32, Coerce_Arg)) == NULL))
   461                             return;
   462                         discharge(hir);
   463                     } else {
   464                         __ int_(0);
   465                     }
   466                 }
   467                 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
   468             } else {
   469                 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
   470             }
   471         } else {
   472             assert(false);
   473         }
   474     }
   475 
   476     if (node->sym()->scope()->kind() != Scope::GLOBAL) {
   477         if (!__ allocate(node->sym()))
   478             return;
   479     }
   480 
   481     set(node->sym());
   482     __ pop();
   483 }
   484 
   485 void
   486 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
   487 {
   488     control_->returns(Returns_Always);
   489 
   490     if (!node->expression()) {
   491         if (!fun_->returnType()->isVoid()) {
   492             cc_.reportError(node->pos(), Message_MissingReturnValue);
   493             return;
   494         }
   495 
   496         __ returnvoid();
   497         return;
   498     }
   499 
   500     if (fun_->returnType()->isVoid()) {
   501         cc_.reportError(node->pos(), Message_UsedVoidReturn);
   502         return;
   503     }
   504 
   505     PoolScope poolScope(zone_->pool());
   506     RootScope rootScope(zone_);
   507 
   508     HIR *hir = eval(node->expression());
   509     if (!hir)
   510         return;
   511 
   512     Local<Type> returnType(zone_, fun_->returnType());
   513     if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
   514         return;
   515 
   516     discharge(hir);
   517 
   518     if (hir->type()->isVoid())
   519         __ returnvoid();
   520     else
   521         __ return_();
   522 }
   523 
   524 void
   525 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
   526 {
   527     HIR *left = eval(node->left());
   528     HIR *right = eval(node->right());
   529     if (!left || !right)
   530         return;
   531 
   532     hir_ = binary(node, node->token(), left, right);
   533 }
   534 
   535 bool
   536 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
   537 {
   538     if (type->parameters()->length() == actual)
   539         return true;
   540 
   541     if (actual > type->parameters()->length()) {
   542         if (!type->isNative() || !type->isNativeVariadic())
   543             return false;
   544         return true;
   545     }
   546 
   547     if (!type->defaults())
   548         return false;
   549 
   550     // Missing arguments. See if there's a default argument for each missing
   551     // actual.
   552     for (unsigned i = actual; i < type->parameters()->length(); i++) {
   553         if (!type->defaults()->at(i))
   554             return false;
   555     }
   556 
   557     return true;
   558 }
   559 
   560 static unsigned
   561 BindImplicitName(Module *from, ImplicitSymbol *sym)
   562 {
   563     if (sym->bound())
   564         return sym->fieldIndex();
   565 
   566     Module *module = Module::cast(from->getImportAt(sym->index()));
   567     StructMap *map = module->globals()->map();
   568 
   569     unsigned fieldIndex;
   570     Descriptor *desc = map->type()->lookupField(sym->name(), &fieldIndex);
   571     assert(desc && desc->type() == sym->type());
   572 
   573     sym->bind(fieldIndex);
   574     return fieldIndex;
   575 }
   576 
   577 void
   578 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
   579 {
   580     Symbol *sym = proxy->sym();
   581 
   582     switch (sym->kind()) {
   583       case Symbol::kImport:
   584       {
   585         ImportSymbol *import = sym->toImport();
   586         hir_ = new (pool_) HImport(proxy, sym->type(), import->index());
   587         break;
   588       }
   589 
   590       case Symbol::kImplicit:
   591       {
   592         ImplicitSymbol *import = sym->toImplicit();
   593         unsigned fieldIndex = BindImplicitName(unit_->module(), import);
   594 
   595         hir_ = new (pool_) HImport(proxy, zone_->types()->getImportable(), import->index());
   596         hir_ = new (pool_) HField(proxy, hir_, sym->type(), fieldIndex);
   597         break;
   598       }
   599 
   600       case Symbol::kConstant:
   601       {
   602         ConstantSymbol *val = sym->toConstant();
   603         hir_ = new (pool_) HInteger(proxy, sym->type(), val->value().toInt());
   604         break;
   605       }
   606       
   607       // This is kind of screwy. Symbol::kFunction is like a constant we can't
   608       // evaluate yet. Maybe we should extract the GLOBAL case and say that
   609       // kFunction is only used for global functions (and use const vars for
   610       // local functions).
   611       case Symbol::kFunction:
   612       case Symbol::kVariable:
   613       {
   614         Scope *in = sym->scope();
   615         switch (in->kind()) {
   616           case Scope::GLOBAL:
   617             hir_ = new (pool_) HGlobal(proxy, sym);
   618             break;
   619 
   620           case Scope::FUNCTION:
   621           {
   622             VariableSymbol *var = sym->toVariable();
   623             assert(var->storage() == VariableSymbol::Arg);
   624             hir_ = new (pool_) HLocal(proxy, var);
   625             break;
   626           }
   627 
   628           default:
   629           {
   630             VariableSymbol *var = sym->toVariable();
   631             assert(in->kind() == Scope::BLOCK);
   632             assert(var->storage() == VariableSymbol::Local);
   633             hir_ = new (pool_) HLocal(proxy, var);
   634             break;
   635           }
   636         }
   637         break;
   638       }
   639 
   640       default:
   641         // :TODO:
   642         assert(false);
   643     }
   644 }
   645 
   646 void
   647 SemanticAnalysis::visitBooleanLiteral(BooleanLiteral *node)
   648 {
   649     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
   650     hir_ = new (pool_) HBoolean(node, type, node->token() == TOK_TRUE);
   651 }
   652 
   653 void
   654 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
   655 {
   656     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   657     hir_ = new (pool_) HInteger(lit, type, lit->value());
   658 }
   659 
   660 void
   661 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
   662 {
   663     Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
   664     hir_ = new (pool_) HFloat(node, type, (float)node->value());
   665 }
   666 
   667 void
   668 SemanticAnalysis::visitStringLiteral(StringLiteral *node)
   669 {
   670     Type *type = zone_->types()->getString();
   671     hir_ = new (pool_) HString(node, type, node->string());
   672 }
   673 
   674 void
   675 SemanticAnalysis::visitCallExpression(CallExpression *node)
   676 {
   677     HIR *callee = eval(node->callee());
   678     if (!callee)
   679         return;
   680 
   681     if (!callee->type()->isFunction()) {
   682         cc_.reportError(node->pos(), Message_CalleeNotFunction);
   683         return;
   684     }
   685 
   686     Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
   687     
   688     if (!checkArgumentCount(fun, node->arguments()->length())) {
   689         cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
   690         return;
   691     }
   692 
   693     if (fun->isForward()) {
   694         cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
   695         return;
   696     }
   697 
   698     HIRList *args = new (pool_) HIRList;
   699     for (unsigned i = 0; i < node->arguments()->length(); i++) {
   700         Expression *expression = node->arguments()->at(i);
   701         HIR *arg = eval(expression);
   702         if (!arg)
   703             return;
   704 
   705         Handle<Type> given = arg->type();
   706         
   707         bool mustComputeReference;
   708         if (i >= fun->parameters()->length()) {
   709             // Special handling for natives. Arguments past the formal must
   710             // always have references computed. However, arrays are already
   711             // references for natives.
   712             assert(fun->isNative() && fun->isNativeVariadic());
   713             mustComputeReference = !given->isReference() &&
   714                                    !given->isArray();
   715         } else {
   716             Local<Type> actual(zone_, fun->parameterAt(i));
   717 
   718             if (expression->isIndexExpression() && arg->isIndex()) {
   719                 // If the expression is the form x[y], and this produced a
   720                 // normal array indexing operation, then we apply some 
   721                 // special rules.
   722 
   723                 if (actual->isReference()) {
   724                     // Disabled, since this doesn't have easily definable or
   725                     // sensible semantics with SP2 arrays, but we don't want
   726                     // to silently break SP1 semantics.
   727                     cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
   728                     return;
   729                 }
   730 
   731                 // As a special rule to account for SP1 semantics, we allow x[y]
   732                 // to automatically compute a sliced, read-only array view if
   733                 // the desired type is an array of one more dimension than x[y]
   734                 // would return.
   735                 //
   736                 // As an additional restriction, this is only allowed for
   737                 // one-level char arrays, to minimize potential issues until
   738                 // we determine whether more compatibility is needed.
   739                 //
   740                 // Internally, for sanity, the dependent array operation does
   741                 // not necessarily create a dependent array. For extensible
   742                 // arrays, we instead create a duplicate arrary of just the
   743                 // sliced portion, rather than deal with the complexity of the
   744                 // source array being resized.
   745                 //
   746                 // Note that we don't really know whether a dependent array
   747                 // will be dependent at compile-time, so the dependent type's
   748                 // just inherits from the source.
   749                 if (actual->isArray()) {
   750                     HIndex *index = arg->toIndex();
   751                     Local<ArrayType> basetype(zone_, ArrayType::cast(index->base()->type()));
   752                     Local<ArrayType> atype(zone_, ArrayType::cast(actual));
   753 
   754                     if (atype->isCharArray() && basetype->isCharArray()) {
   755                         // There is no possible way this will type check, so
   756                         // it's safe to just try something completely
   757                         // different.
   758                         Local<Type> slicetype(zone_);
   759                         if (basetype->isFixedLength()) {
   760                             // If the base type is fixed length, we need to
   761                             // compute a new dynamic array type based on the
   762                             // fixed array's contents and qualifiers.
   763                             Local<Type> contained(zone_, basetype->contained());
   764                             slicetype = zone_->types()->newArray(contained, ArrayType::DYNAMIC_ARRAY_SIZE);
   765                             if (!slicetype)
   766                                 return;
   767                             slicetype = zone_->types()->qualify(slicetype, basetype->quals());
   768                             if (!slicetype)
   769                                 return;
   770                         } else {
   771                             slicetype = basetype;
   772                         }
   773                         arg = new (pool_) HNewDependentArray(expression, slicetype, index->base(), index->index());
   774                         given = arg->type();
   775                     }
   776                 }
   777             }
   778 
   779             if (actual->isReference()) {
   780                 // If the actual is a reference, the coercion rules are much
   781                 // stricter; the contained types must be identical.
   782                 // :TODO: make this not an assert
   783                 assert(ReferenceType::cast(actual)->contained() == arg->type());
   784             } else {
   785                 // When we start overloading, coercion will have to happen later.
   786                 arg = coerce(arg, actual, Coerce_Arg);
   787                 if (!arg)
   788                     return;
   789             }
   790 
   791             mustComputeReference = actual->isReference() && !given->isReference();
   792         }
   793 
   794         if (mustComputeReference) {
   795             // Refs always use the LIFO stack if they can.
   796             arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
   797             requireLifoStack();
   798         }
   799 
   800         if (!args->append(arg))
   801             return;
   802     }
   803 
   804     hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
   805 }
   806 
   807 void
   808 SemanticAnalysis::visitAssignment(Assignment *node)
   809 {
   810     HLValue *lval = lvalue(node->lvalue());
   811     if (!lval)
   812         return;
   813 
   814     if (lval->type()->quals() & TypeQual_Const) {
   815         cc_.reportError(node->pos(), Message_CannotModifyConst);
   816         return;
   817     }
   818 
   819     HIR *hir = eval(node->expression());
   820     if (!hir)
   821         return;
   822     if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
   823         return;
   824 
   825     hir_ = new (pool_) HStore(node, node->token(), lval, hir);
   826 }
   827 
   828 void
   829 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
   830 {
   831     if (!loop_) {
   832         cc_.reportError(node->pos(), Message_BreakOutsideLoop);
   833         return;
   834     }
   835 
   836     loop_->setBreaks();
   837     __ j(OP_BREAK, loop_->break_());
   838 }
   839 
   840 void
   841 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
   842 {
   843     if (!loop_) {
   844         cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
   845         return;
   846     }
   847 
   848     __ j(OP_CONTINUE, loop_->continue_());
   849 }
   850 
   851 void
   852 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
   853 {
   854     HIR *left = eval(node->left());
   855     if (!left)
   856         return;
   857 
   858     HIR *right = eval(node->right());
   859     if (!right)
   860         return;
   861 
   862     // Hrm... yes, for now, let's coerce here.
   863     Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
   864     if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
   865         return;
   866     
   867     // Do not coerce here, there's no reason to yet.
   868     if (!left->type()->isArray()) {
   869         cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
   870         return;
   871     }
   872 
   873     hir_ = new (pool_) HIndex(node,
   874                               ArrayType::cast(left->type())->contained(),
   875                               left,
   876                               right);
   877 }
   878 
   879 void
   880 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
   881 {
   882     HLValue *lval = lvalue(node->expression());
   883     if (!lval)
   884         return;
   885 
   886     if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
   887         assert(false);
   888         return;
   889     }
   890 
   891     HIR *rval;
   892     if (lval->type()->isInt32())
   893         rval = new (pool_) HInteger(node, lval->type(), 1);
   894     else
   895         rval = new (pool_) HFloat(node, lval->type(), 1.0);
   896 
   897     if (node->postfix())
   898         hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
   899     else
   900         hir_ = new (pool_) HStore(node, node->token(), lval, rval);
   901 }
   902 
   903 Type *
   904 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
   905 {
   906     Local<Type> l(zone_, left->type());
   907     Local<Type> r(zone_, right->type());
   908 
   909     if (l->isPod())
   910         l = l->unqualified();
   911     if (r->isPod())
   912         r = r->unqualified();
   913 
   914     if ((token >= TOK_PLUS && token <= TOK_SLASH) ||
   915         (token >= TOK_EQUALS && token <= TOK_GE))
   916     {
   917         // We allow: [float|int32] + [float|int32]
   918         if (l->isFloat() && r->isInt32())
   919             return l;
   920         if (l->isInt32() && r->isFloat())
   921             return r;
   922         if (l->isInt32() && r->isInt32())
   923             return l;
   924 
   925         if (l->isChar() && r->isInt32())
   926              return r;
   927         if (l->isInt32() && r->isChar())
   928             return l;
   929     }
   930 
   931     // :TODO: remove
   932     assert(*l == *r);
   933 
   934     return left->type();
   935 }
   936 
   937 HIR *
   938 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
   939                                  HIR *from,
   940                                  Handle<ArrayType> argActual,
   941                                  CoercionKind kind)
   942 {
   943     Local<Type> argGiven(zone_, from->type());
   944 
   945     // Special case: if we receive a string literal, and this is a char array,
   946     // we allow a coercion.
   947     if (from->isString() &&
   948         argGiven->isString() &&
   949         argActual->isArray() &&
   950         ArrayType::cast(argActual)->isCharArray())
   951     {
   952         HString *hir = from->toString();
   953         Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
   954 
   955         if (actual->isFixedLength()) {
   956             if (hir->string()->length() + 1 > actual->fixedLength()) {
   957                 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
   958                 return NULL;
   959             }
   960         }
   961 
   962         // Transform the string literal into an array literal. We give it the
   963         // type of the left-hand side. The constness of the destination type
   964         // will determine whether HArray duplicates it or not.
   965         Local<ArrayMap> map(zone_, actual->newMap());
   966         if (!map)
   967             return NULL;
   968 
   969         Local<Array> array(zone_);
   970         array = Array::NewString(zone_,
   971                                  map,
   972                                  hir->string()->chars(),
   973                                  hir->string()->length(),
   974                                  Heap::Tenure_Old);
   975         if (!array)
   976             return NULL;
   977 
   978         // Since we're creating a canonical copy of the char array, we have to
   979         // be careful that it doesn't get mutated. There are two cases where
   980         // we know it can't be mutated, and therefore don't need to specify
   981         // that it be cloned after pushing it onto the stack.
   982         //
   983         //  (1) The array type is const.
   984         //  (2) The array type is fixed-length, and the coercion is for
   985         //      assignment, meaning it will be immediately copied.
   986         //
   987         // We treat declaration separately from assignment, since for
   988         // declaration we can just immediately use the cloned version.
   989         bool shouldDuplicate = true;
   990         if ((actual->quals() & TypeQual_Const) ||
   991             (actual->isFixedLength() && kind == Coerce_Assign))
   992         {
   993             shouldDuplicate = false;
   994         }
   995 
   996         return new (pool_) HArray(hir->node(), actual, array, shouldDuplicate);
   997     }
   998 
   999     if (!argGiven->isArray()) {
  1000         cc_.reportError(pos, Message_ExpectedArray);
  1001         return NULL;
  1002     }
  1003 
  1004     Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
  1005     Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
  1006 
  1007     if (actual->levels() != given->levels()) {
  1008         cc_.reportError(pos, Message_ArrayDimensionsMismatch);
  1009         return NULL;
  1010     }
  1011 
  1012     unsigned level = 1;
  1013     while (true) {
  1014         if (actual->isFixedLength()) {
  1015             if (!given->isFixedLength()) {
  1016                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1017                 return NULL;
  1018             }
  1019 
  1020             if (actual->isCharArray()) {
  1021                 // String assignment can have a truncated |given|.
  1022                 if (given->fixedLength() > actual->fixedLength()) {
  1023                     cc_.reportError(pos, Message_ArrayAssignmentTooBig);
  1024                     return NULL;
  1025                 }
  1026             } else {
  1027                 if (given->fixedLength() != actual->fixedLength()) {
  1028                     cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1029                     return NULL;
  1030                 }
  1031             }
  1032         } else if (given->isFixedLength()) {
  1033             // We do not allow assignments in the form:
  1034             //  [][] = [][Y]
  1035             //
  1036             // Otherwise, the following code could break the size guarantees
  1037             // of the right-hand side:
  1038             //
  1039             //  new x[][5];
  1040             //  new y[][];
  1041             //  new z[3];
  1042             //
  1043             //
  1044             //  y = x;
  1045             //  y[0] = z;
  1046             //
  1047             // Now |x[0]| contains a 3-length array.
  1048             if (level > 1) {
  1049                 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
  1050                 return NULL;
  1051             }
  1052         }
  1053 
  1054         if (!given->contained()->isArray() || !actual->contained()->isArray())
  1055             break;
  1056 
  1057         given = ArrayType::cast(given->contained());
  1058         actual = ArrayType::cast(actual->contained());
  1059     }
  1060 
  1061     bool givenConst = !!(given->contained()->quals() & TypeQual_Const);
  1062     bool actualConst = !!(actual->contained()->quals() & TypeQual_Const);
  1063 
  1064     // These arrays must contain the same innermost type.
  1065     if (given->contained()->unqualified() != actual->contained()->unqualified() ||
  1066         (givenConst && !actualConst))
  1067     {
  1068         char aname[255];
  1069         char gname[255];
  1070         cc_.reportError(pos, Message_TypeMismatch,
  1071                         GetTypeName(argActual, aname, sizeof(aname)),
  1072                         GetTypeName(argGiven, gname, sizeof(gname)));
  1073         return NULL;
  1074     }
  1075 
  1076     return from;
  1077 }
  1078 
  1079 HIR *
  1080 SemanticAnalysis::typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to)
  1081 {
  1082     char fname[255];
  1083     char tname[255];
  1084     cc_.reportError(pos, Message_InvalidCoercion,
  1085                     GetTypeName(from, fname, sizeof(fname)),
  1086                     GetTypeName(to, tname, sizeof(tname)));
  1087     return NULL;
  1088 }
  1089 
  1090 HIR *
  1091 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
  1092 {
  1093     Local<Type> from(zone_, hir->type());
  1094 
  1095     // If the source is *ever* an importable, we just fail.
  1096     if (from->isImportable())
  1097         return typeFailure(hir->node()->pos(), from, to);
  1098 
  1099     if (from->isInt32() && to->isFloat())
  1100         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
  1101     if (from->isInt32() && to->isBool())
  1102         return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
  1103 
  1104     if (to->isEnum() && from->unqualified() != to->unqualified())
  1105         return typeFailure(hir->node()->pos(), from, to);
  1106     
  1107     if (to->isArray()) {
  1108         Local<ArrayType> atype(zone_, ArrayType::cast(to));
  1109         return typeCheckArray(hir->node()->pos(), hir, atype, kind);
  1110     }
  1111     
  1112     return hir;
  1113 }
  1114 
  1115 void
  1116 SemanticAnalysis::set(VariableSymbol *sym)
  1117 {
  1118     if (sym->scope()->kind() == Scope::GLOBAL) {
  1119         __ setglobal(sym);
  1120     } else {
  1121         assert(sym->storage() == VariableSymbol::Local);
  1122         __ setlocal(sym);
  1123     }
  1124 }
  1125 
  1126 HIR *
  1127 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
  1128 {
  1129     Local<Type> coercion(zone_, coercionType(token, left, right));
  1130     if (!coercion)
  1131         return NULL;
  1132     if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
  1133         return NULL;
  1134     if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
  1135         return NULL;
  1136     
  1137     switch (token) {
  1138      case TOK_PLUS:
  1139       case TOK_MINUS:
  1140       case TOK_STAR:
  1141       case TOK_SLASH:
  1142       case TOK_PERCENT:
  1143       case TOK_AMPERSAND:
  1144       case TOK_BITOR:
  1145       case TOK_BITXOR:
  1146       case TOK_SHR:
  1147       case TOK_USHR:
  1148       case TOK_SHL:
  1149         return new (pool_) HBinary(node, left->type(), token, left, right);
  1150 
  1151       case TOK_EQUALS:
  1152       case TOK_NOTEQUALS:
  1153       case TOK_LT:
  1154       case TOK_LE:
  1155       case TOK_GT:
  1156       case TOK_GE:
  1157       case TOK_AND:
  1158       case TOK_OR:
  1159       {
  1160         Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1161         return new (pool_) HBinary(node, result, token, left, right);
  1162       }
  1163 
  1164       default:
  1165         assert(false);
  1166         return NULL;
  1167     }
  1168 }
  1169 
  1170 static inline bool
  1171 IsValidUncheckedType(Type *type)
  1172 {
  1173     return type->isEnum() ||
  1174            type->isFloat() ||
  1175            type->isInt32() ||
  1176            type->isChar() ||
  1177            type->isUnchecked() ||
  1178            type->isBool();
  1179 }
  1180 
  1181 void
  1182 SemanticAnalysis::visitUnaryExpression(UnaryExpression *node)
  1183 {
  1184     HIR *hir = eval(node->expression());
  1185     if (!hir)
  1186         return;
  1187 
  1188     switch (node->token()) {
  1189       case TOK_TILDE:
  1190       {
  1191         if (!hir->type()->isInt32() && !hir->type()->isEnum()) {
  1192             char name[255];
  1193             cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1194                             "~",
  1195                             GetTypeName(hir->type(), name, sizeof(name)));
  1196         }
  1197         Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1198         hir_ = new (pool_) HUnary(node, hir->type(), TOK_TILDE, hir);
  1199         return;
  1200       }
  1201 
  1202       case TOK_MINUS:
  1203       {
  1204         if (hir->type()->isInt32() || hir->type()->isEnum()) {
  1205             Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
  1206             hir_ = new (pool_) HUnary(node, type, TOK_MINUS, hir);
  1207             return;
  1208         }
  1209         if (hir->type()->isFloat()) {
  1210             hir_ = new (pool_) HUnary(node, hir->type(), TOK_MINUS, hir);
  1211             return;
  1212         }
  1213 
  1214         char name[255];
  1215         cc_.reportError(node->pos(), Message_InvalidUnaryType,
  1216                         "-",
  1217                         GetTypeName(hir->type(), name, sizeof(name)));
  1218         break;
  1219       }
  1220 
  1221       default:
  1222       {
  1223         assert(node->token() == TOK_LABEL);
  1224 
  1225         TypeSymbol *sym = node->tag()->sym()->asType();
  1226         if (!sym) {
  1227             cc_.reportError(node->pos(), Message_IdentifierIsNotAType,
  1228                             sym->name()->chars());
  1229             return;
  1230         }
  1231 
  1232         if (!IsValidUncheckedType(sym->effective())) {
  1233             char name[255];
  1234             cc_.reportError(node->pos(), Message_InvalidUncheckedCastTo,
  1235                             GetTypeName(sym->type(), name, sizeof(name)));
  1236             return;
  1237         }
  1238         if (!IsValidUncheckedType(hir->type())) {
  1239             char name[255];
  1240             cc_.reportError(node->pos(), Message_InvalidUncheckedCastFrom,
  1241                             GetTypeName(hir->type(), name, sizeof(name)));
  1242             return;
  1243         }
  1244 
  1245         hir_ = new (pool_) HUnary(node, sym->effective(), TOK_LABEL, hir);
  1246         break;
  1247       }
  1248     }
  1249 }
  1250 
  1251 void
  1252 SemanticAnalysis::import(HIR *hir, FieldExpression *node)
  1253 {
  1254     // Note that we don't care if the hir type is "importable", since we
  1255     // can only do anything if the important has a constant binding.
  1256     unsigned index = hir->toImport()->index();
  1257     Local<Importable> importable(zone_, unit_->module()->getImportAt(index));
  1258 
  1259     if (importable->isPackage()) {
  1260         // Look at what's already loaded and see if anything exists. We
  1261         // can't create stuff on-demand here since it's too late to add
  1262         // new translation units to the CompileContext.
  1263         Local<Package> package(zone_, Package::cast(importable));
  1264         Local<Importable> found(zone_, package->import(node->field()));
  1265         if (!found) {
  1266             cc_.reportError(node->pos(), Message_PackageDoesNotHaveMember, node->field()->chars());
  1267             return;
  1268         }
  1269 
  1270         // If we did find something, make sure it is in our import list.
  1271         // If we didn't explicitly import it, we have no right to use it.
  1272         for (index = 0; index < unit_->module()->imports(); index++) {
  1273             if (unit_->module()->getImportAt(index) == importable)
  1274                 break;
  1275         }
  1276 
  1277         if (index == unit_->module()->imports()) {
  1278             cc_.reportError(node->pos(), Message_ImportWasNeverImported, node->field()->chars());
  1279             return;
  1280         }
  1281 
  1282         // Just create a new HImport.
  1283         hir_ = new (pool_) HImport(node, hir->type(), index);
  1284     } else {
  1285         // Modules can never have sub-modules or sub-packages.
  1286         unsigned index;
  1287         Local<Module> module(zone_, Module::cast(importable));
  1288         Local<StructMap> map(zone_, module->globals()->map());
  1289         Local<Descriptor> desc(zone_, map->type()->lookupField(node->field(), &index));
  1290         if (!desc) {
  1291             cc_.reportError(node->pos(), Message_FieldNotFound, node->field()->chars());
  1292             return;
  1293         }
  1294         hir_ = new (pool_) HField(node, hir, desc->type(), index);
  1295     }
  1296 }
  1297 
  1298 void
  1299 SemanticAnalysis::visitFieldExpression(FieldExpression *node)
  1300 {
  1301     HIR *hir = eval(node->left());
  1302     if (!hir)
  1303         return;
  1304 
  1305     if (hir->isImport()) {
  1306         import(hir, node);
  1307         return;
  1308     }
  1309 
  1310     char name[255];
  1311     cc_.reportError(node->pos(), Message_InvalidFieldExpression,
  1312                     GetTypeName(hir->type(), name, sizeof(name)));
  1313 }
  1314 
  1315 static inline TokenKind
  1316 ToCompare(Expression *expr)
  1317 {
  1318     if (expr->isBinaryExpression()) {
  1319         BinaryExpression *b = expr->toBinaryExpression();
  1320         if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
  1321             return b->token();
  1322     } else if (expr->isUnaryExpression()) {
  1323         UnaryExpression *u = expr->toUnaryExpression();
  1324         if (u->token() == TOK_NOT)
  1325             return TOK_NOT;
  1326     }
  1327     return TOK_EOF;
  1328 }
  1329 
  1330 void
  1331 SemanticAnalysis::visitForTest(Expression *expr,
  1332                                Label *trueBranch,
  1333                                Label *falseBranch,
  1334                                Label *fallthrough)
  1335 {
  1336     Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
  1337 
  1338     TokenKind token = ToCompare(expr);
  1339     if (token == TOK_EOF || token == TOK_NOT) {
  1340         HIR *hir;
  1341         if (token == TOK_EOF)
  1342             hir = eval(expr);
  1343         else
  1344             hir = eval(expr->toUnaryExpression()->expression());
  1345         if (!hir)
  1346             return;
  1347         if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1348             return;
  1349 
  1350         discharge(hir);
  1351 
  1352         bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
  1353         Opcode op = jumpOnTrue ? OP_JT : OP_JF;
  1354         
  1355         if (fallthrough == falseBranch)
  1356             __ j(op, trueBranch);
  1357         else
  1358             __ j(op, falseBranch);
  1359         return;
  1360     }
  1361 
  1362     BinaryExpression *bin = expr->toBinaryExpression();
  1363     if (token == TOK_AND || token == TOK_OR) {
  1364         Label next;
  1365         if (token == TOK_AND)
  1366             visitForTest(bin->left(), &next, falseBranch, &next);
  1367         else
  1368             visitForTest(bin->left(), trueBranch, &next, &next);
  1369         __ bind(&next);
  1370         visitForTest(bin->right(), trueBranch, falseBranch, fallthrough);
  1371         return;
  1372     }
  1373 
  1374     HIR *left = eval(bin->left());
  1375     HIR *right = eval(bin->right());
  1376     if (!left || !right)
  1377         return;
  1378 
  1379     HIR *hir = binary(bin, bin->token(), left, right);
  1380     if (!hir)
  1381         return;
  1382     if ((hir = coerce(hir, boolType, Coerce_Arg)) == NULL)
  1383         return;
  1384 
  1385     discharge(hir);
  1386     if (fallthrough == trueBranch)
  1387         __ j(OP_JF, falseBranch);
  1388     else
  1389         __ j(OP_JT, trueBranch);
  1390 }
  1391 
  1392 HLValue *
  1393 SemanticAnalysis::lvalue(Expression *expr)
  1394 {
  1395     HIR *hir = eval(expr);
  1396     if (!hir)
  1397         return NULL;
  1398     
  1399     if (!hir->isLValue()) {
  1400         cc_.reportError(expr->pos(), Message_ExpectedLValue);
  1401         return NULL;
  1402     }
  1403 
  1404     return static_cast<HLValue *>(hir);
  1405 }
  1406 
  1407 HIR *
  1408 SemanticAnalysis::eval(Expression *expr)
  1409 {
  1410     assert(!hir_);
  1411     expr->accept(this);
  1412 
  1413     HIR *hir = hir_;
  1414     hir_ = NULL;
  1415 
  1416     return hir;
  1417 }
  1418 
  1419 void
  1420 SemanticAnalysis::discharge(HIR *hir)
  1421 {
  1422     EmitHIR(zone_, emitter_, hir);
  1423 }