Re-add LIFO stack optimizations.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of SourcePawn.
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)
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.
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/.
21 #include "../Strings.h"
22 #include "../NativeTable.h"
23 #include "../TypeManager.h"
24 #include "../Modules.h"
26 #include "SemanticAnalysis.h"
27 #include "../Heap-inl.h"
33 typedef BytecodeEmitter::Label Label;
38 AutoEnterScope(Scope **prevp, Scope *scope)
47 assert(prev_ == scope->enclosing());
60 SemanticAnalysis::SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit)
72 SemanticAnalysis::SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun)
73 : zone_(parent->zone_),
78 scope_(parent->scope_),
80 module_(parent->module_),
88 SemanticAnalysis::analyze()
90 scope_ = unit_->globalScope();
92 module_ = Module::New(zone_);
94 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
95 Statement *stmt = unit_->tree()->statements()->at(i);
99 Local<Struct> globals(zone_, unit_->globalScope()->build(zone_));
102 module_->setGlobals(globals);
104 Local<Code> code(zone_, __ finish());
107 code->setModule(module_);
108 module_->setCode(code);
111 // Disassemble(code, stdout);
114 unit_->module_ = module_;
118 SemanticAnalysis::visitFunctionStatement(FunctionStatement *stmt)
120 FunctionSymbol *sym = stmt->sym();
121 Local<FunctionType> type(zone_, sym->type());
123 assert(scope_->kind() == Scope::GLOBAL);
125 if (stmt->token() == TOK_NATIVE) {
126 // Define the native now.
128 if (!zone_->nativeTable()->add(stmt->name(), &index))
131 Local<Native> native(zone_, Native::New(zone_, type, index));
140 // If the function is a forward or native, we don't have to do anything.
141 if (stmt->token() == TOK_NATIVE || stmt->token() == TOK_FORWARD)
144 SemanticAnalysis child(this, type);
145 Local<Function> funobj(zone_, child.compile(stmt));
151 if (stmt->token() == TOK_PUBLIC)
158 SemanticAnalysis::compile(FunctionStatement *stmt)
160 __ setFirstLine(stmt->pos().line);
162 AutoEnterScope argScope(&scope_, stmt->argScope());
164 for (size_t i = 0; i < stmt->signature().parameters()->length(); i++) {
165 Parameter *param = stmt->signature().parameters()->at(i);
166 param->sym()->allocate(VariableSymbol::Arg, i);
169 AutoEnterScope varScope(&scope_, stmt->varScope());
171 stmt->body()->accept(this);
173 Local<Code> code(zone_, __ finish());
176 code->setModule(module_);
178 Local<Function> fun(zone_, Function::New(zone_, code, fun_, stmt->name(), stmt->pos()));
183 // Disassemble(code, stdout);
190 SemanticAnalysis::visitBlockStatement(BlockStatement *node)
192 AutoEnterScope scope(&scope_, node->scope());
194 for (size_t i = 0; i < node->statements()->length(); i++) {
195 Statement *stmt = node->statements()->at(i);
196 __ note_position(stmt->pos());
198 assert(__ stackDepth() == 0);
203 SemanticAnalysis::visitExpressionStatement(ExpressionStatement *node)
205 // While building HIR, we enter new pool and root scopes, since HIR
206 // creation is purely temporary.
207 PoolScope poolScope(zone_->pool());
208 RootScope rootScope(zone_);
210 HIR *hir = eval(node->expression());
215 if (!hir->type()->isVoid())
220 SemanticAnalysis::visitIfStatement(IfStatement *node)
224 if (!node->ifFalse()) {
227 visitForTest(node->condition(), &success, &join, &success);
229 node->ifTrue()->accept(this);
233 visitForTest(node->condition(), &success, &next, &success);
235 node->ifTrue()->accept(this);
238 node->ifFalse()->accept(this);
245 SemanticAnalysis::requireLifoStack()
250 loop_->setUsesLifoStack();
254 SemanticAnalysis::visitLoopBody(Statement *stmt)
256 // We always mark off a loop body, so on each edge, we can balance the
257 // LIFO stack. Right now, we don't have the ability to budget the LIFO
258 // stack ahead of time. If we turn out to never need the LIFO stack, we
259 // mark it as unnecessary. (The interpreter can't really make use of this,
262 // Note that balancing the LIFO stack isn't even necessary, so this
263 // feature may be removed. All this mechanism does is mitigate the
264 // possibility that a long-running loop will overflow the LIFO region
265 // and therefore start requiring nursery allocations.
266 int pos = __ enterloop();
270 if (loop_->usesLifoStack())
271 __ setLoopUsesLifoStack(pos);
275 SemanticAnalysis::visitForStatement(ForStatement *node)
277 AutoEnterScope scope(&scope_, node->scope());
278 PoolScope poolScope(zone_->pool());
279 RootScope rootScope(zone_);
282 LoopScope loop(scope_, &join, &update, &loop_);
284 if (node->initialization())
285 node->initialization()->accept(this);
288 if (node->condition())
292 visitLoopBody(node->body());
296 node->update()->accept(this);
298 if (node->condition()) {
300 visitForTest(node->condition(), &header, &join, &join);
307 assert(__ stackDepth() == 0);
311 SemanticAnalysis::visitWhileStatement(WhileStatement *node)
313 PoolScope poolScope(zone_->pool());
314 RootScope rootScope(zone_);
320 LoopScope loop(scope_, &join, &header, &loop_);
321 if (node->token() == TOK_WHILE) {
323 visitForTest(node->condition(), &body, &join, &body);
324 visitLoopBody(node->body());
327 visitLoopBody(node->body());
328 visitForTest(node->condition(), &header, &join, &join);
333 assert(__ stackDepth() == 0);
336 static inline Heap::Tenure
337 InferTenure(Symbol *sym)
339 if (sym->scope()->kind() == Scope::GLOBAL)
340 return Heap::Tenure_Old;
342 // SP2's array semantics allow any array kind to escape, so we must use
343 // the normal heap. (Hopefully escape analysis can ease this pain later).
344 if (sym->type()->isArray())
345 return Heap::Tenure_Default;
347 return Heap::Tenure_Default;
351 SemanticAnalysis::visitVariableDeclaration(VariableDeclaration *node)
353 PoolScope poolScope(zone_->pool());
354 RootScope rootScope(zone_);
356 if (node->initialization()) {
359 if ((hir = eval(node->initialization())) == NULL)
361 if ((hir = coerce(hir, node->sym()->type(), Coerce_Assign)) == NULL)
366 if (node->sym()->type()->isInt32() ||
367 node->sym()->type()->isEnum() ||
368 node->sym()->type()->isChar() ||
369 node->sym()->type()->isBool())
372 } else if (node->sym()->type()->isFloat()) {
374 } else if (node->sym()->type()->isArray()) {
375 Local<ArrayType> type(zone_, ArrayType::cast(node->sym()->type()));
376 Local<ArrayMap> map(zone_, ArrayMap::Attach(zone_, type));
380 if (type->isFixedLength()) {
381 __ newarray(OP_NEWFIXED, map, InferTenure(node->sym()));
382 } else if (node->dims()) {
384 __ newarray(OP_NEWSIZED, map, InferTenure(node->sym()));
386 __ newarray(OP_NEWEMPTY, map, InferTenure(node->sym()));
391 if (!__ allocate(node->sym()))
399 SemanticAnalysis::visitReturnStatement(ReturnStatement *node)
401 if (!node->expression()) {
402 if (!fun_->returnType()->isVoid()) {
403 cc_.reportError(node->pos(), Message_UsedVoidReturn);
411 PoolScope poolScope(zone_->pool());
412 RootScope rootScope(zone_);
414 HIR *hir = eval(node->expression());
418 Local<Type> returnType(zone_, fun_->returnType());
419 if ((hir = coerce(hir, returnType, Coerce_Return)) == NULL)
427 SemanticAnalysis::visitBinaryExpression(BinaryExpression *node)
429 HIR *left = eval(node->left());
430 HIR *right = eval(node->right());
434 hir_ = binary(node, node->token(), left, right);
438 SemanticAnalysis::checkArgumentCount(Handle<FunctionType> type, unsigned actual)
440 if (type->parameters()->length() == actual)
443 if (actual > type->parameters()->length()) {
444 if (!type->isNative() || !type->isNativeVariadic())
449 if (!type->defaults())
452 // Missing arguments. See if there's a default argument for each missing
454 for (unsigned i = actual; i < type->parameters()->length(); i++) {
455 if (!type->defaults()->at(i))
463 SemanticAnalysis::visitNameProxy(NameProxy *proxy)
465 Symbol *sym = proxy->sym();
466 VariableSymbol *var = sym->asVariable();
468 Scope *in = sym->scope();
469 switch (in->kind()) {
471 hir_ = new (pool_) HGlobal(proxy, sym);
474 case Scope::FUNCTION:
475 assert(var->storage() == VariableSymbol::Arg);
476 hir_ = new (pool_) HLocal(proxy, var);
480 assert(in->kind() == Scope::BLOCK);
481 assert(var->storage() == VariableSymbol::Local);
482 hir_ = new (pool_) HLocal(proxy, var);
488 SemanticAnalysis::visitIntegerLiteral(IntegerLiteral *lit)
490 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
491 hir_ = new (pool_) HInteger(lit, type, lit->value());
495 SemanticAnalysis::visitFloatLiteral(FloatLiteral *node)
497 Local<Type> type(zone_, zone_->types()->getPrimitive(PrimitiveType_Float));
498 hir_ = new (pool_) HFloat(node, type, (float)node->value());
502 SemanticAnalysis::visitCallExpression(CallExpression *node)
504 HIR *callee = eval(node->callee());
508 if (!callee->type()->isFunction()) {
509 cc_.reportError(node->pos(), Message_CalleeNotFunction);
513 Local<FunctionType> fun(zone_, FunctionType::cast(callee->type()));
515 if (!checkArgumentCount(fun, node->arguments()->length())) {
516 cc_.reportError(node->pos(), Message_ArgumentCountMismatch);
520 if (fun->isForward()) {
521 cc_.reportError(node->pos(), Message_ForwardNotImplemented, fun->name()->chars());
525 HIRList *args = new (pool_) HIRList;
526 for (unsigned i = 0; i < node->arguments()->length(); i++) {
527 Expression *expression = node->arguments()->at(i);
528 HIR *arg = eval(expression);
532 Handle<Type> given = arg->type();
534 bool mustComputeReference;
535 if (i >= fun->parameters()->length()) {
536 // Special handling for natives. Arguments past the formal must
537 // always have references computed. However, arrays are already
538 // references for natives.
539 assert(fun->isNative() && fun->isNativeVariadic());
540 mustComputeReference = !given->isReference() &&
543 Local<Type> actual(zone_, fun->parameterAt(i));
545 if (expression->isIndexExpression()) {
546 // Temporarily disabled.
547 assert(!actual->isArray());
548 if (actual->isReference()) {
549 cc_.reportError(expression->pos(), Message_CannotComputeIndexRef);
554 if (actual->isReference()) {
555 // If the actual is a reference, the coercion rules are much
556 // stricter; the contained types must be identical.
557 // :TODO: make this not an assert
558 assert(ReferenceType::cast(actual)->contained() == arg->type());
560 // When we start overloading, coercion will have to happen later.
561 arg = coerce(arg, actual, Coerce_Arg);
566 mustComputeReference = actual->isReference() && !given->isReference();
569 if (mustComputeReference) {
570 // Refs always use the LIFO stack if they can.
571 arg = new (pool_) HToRef(arg->node(), arg->type(), arg);
575 if (!args->append(arg))
579 hir_ = new (pool_) HCall(node, fun->returnType(), callee, args);
583 SemanticAnalysis::visitAssignment(Assignment *node)
585 HLValue *lval = lvalue(node->lvalue());
589 HIR *hir = eval(node->expression());
590 if ((hir = coerce(hir, lval->type(), Coerce_Assign)) == NULL)
593 hir_ = new (pool_) HStore(node, node->token(), lval, hir);
597 SemanticAnalysis::visitBreakStatement(BreakStatement *node)
600 cc_.reportError(node->pos(), Message_BreakOutsideLoop);
604 __ j(OP_BREAK, loop_->break_());
608 SemanticAnalysis::visitContinueStatement(ContinueStatement *node)
611 cc_.reportError(node->pos(), Message_ContinueOutsideLoop);
615 __ j(OP_CONTINUE, loop_->continue_());
619 SemanticAnalysis::visitIndexExpression(IndexExpression *node)
621 HIR *left = eval(node->left());
625 HIR *right = eval(node->right());
629 // Hrm... yes, for now, let's coerce here.
630 Local<Type> i32(zone_, zone_->types()->getPrimitive(PrimitiveType_Int32));
631 if ((right = coerce(right, i32, Coerce_Arg)) == NULL)
634 // Do not coerce here, there's no reason to yet.
635 if (!left->type()->isArray()) {
636 cc_.reportError(node->left()->pos(), Message_IndexBaseMustBeArray);
640 hir_ = new (pool_) HIndex(node,
641 ArrayType::cast(left->type())->contained(),
647 SemanticAnalysis::visitIncDecExpression(IncDecExpression *node)
649 HLValue *lval = lvalue(node->expression());
653 if (!lval->type()->isInt32() && !lval->type()->isFloat()) {
659 if (lval->type()->isInt32())
660 rval = new (pool_) HInteger(node, lval->type(), 1);
662 rval = new (pool_) HFloat(node, lval->type(), 1.0);
665 hir_ = new (pool_) HPostIncDec(node, node->token(), lval, rval);
667 hir_ = new (pool_) HStore(node, node->token(), lval, rval);
671 SemanticAnalysis::coercionType(TokenKind token, HIR *left, HIR *right)
673 Handle<Type> l = left->type();
674 Handle<Type> r = right->type();
676 if (token >= TOK_PLUS && token <= TOK_SLASH) {
677 // We allow: [float|int32] + [float|int32]
678 if (l->isFloat() && r->isInt32())
680 if (l->isInt32() && r->isFloat())
682 if (l->isInt32() && r->isInt32())
693 SemanticAnalysis::typeCheckArray(const SourcePosition &pos,
694 Handle<Type> argGiven,
695 Handle<Type> argActual,
698 if (!argGiven->isArray()) {
699 cc_.reportError(pos, Message_ExpectedArray);
703 Local<ArrayType> actual(zone_, ArrayType::cast(argActual));
704 Local<ArrayType> given(zone_, ArrayType::cast(argGiven));
706 if (actual->levels() != given->levels()) {
707 cc_.reportError(pos, Message_ArrayDimensionsMismatch);
713 if (actual->isFixedLength()) {
714 if (kind == Coerce_Return || kind == Coerce_Assign) {
715 if (!given->isFixedLength()) {
716 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
720 if (actual->isCharArray()) {
721 // String assignment can have a truncated |given|.
722 if (given->fixedLength() > actual->fixedLength()) {
723 cc_.reportError(pos, Message_ArrayAssignmentTooBig);
727 if (given->fixedLength() != actual->fixedLength()) {
728 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
733 } else if (given->isFixedLength()) {
734 // We do not allow assignments in the form:
737 // Otherwise, the following code could break the size guarantees
738 // of the right-hand side:
748 // Now |x[0]| contains a 3-length array.
750 cc_.reportError(pos, Message_ArrayDimensionSizeMismatch, level);
755 if (!given->contained()->isArray() || !actual->contained()->isArray())
758 given = ArrayType::cast(given->contained());
759 actual = ArrayType::cast(actual->contained());
762 // These arrays must contain the same innermost type.
763 if (given->contained() != actual->contained()) {
764 cc_.reportError(pos, Message_TypeMismatch,
765 GetTypeName(actual->contained()),
766 GetTypeName(given->contained()));
774 SemanticAnalysis::coerce(HIR *hir, Handle<Type> to, CoercionKind kind)
776 Handle<Type> from = hir->type();
778 if (from->isInt32() && to->isFloat())
779 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2F, hir);
780 if (from->isInt32() && to->isBool())
781 return new (pool_) HConvert(hir->node(), to, OP_CVT_I2B, hir);
784 if (!typeCheckArray(SourcePosition(), from, to, kind))
793 SemanticAnalysis::set(VariableSymbol *sym)
795 if (sym->scope()->kind() == Scope::GLOBAL) {
798 assert(sym->storage() == VariableSymbol::Local);
804 SemanticAnalysis::binary(AstNode *node, TokenKind token, HIR *left, HIR *right)
806 Local<Type> coercion(zone_, coercionType(token, left, right));
809 if ((left = coerce(left, coercion, Coerce_Arg)) == NULL)
811 if ((right = coerce(right, coercion, Coerce_Arg)) == NULL)
826 return new (pool_) HBinary(node, left->type(), token, left, right);
837 Local<Type> result(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
838 return new (pool_) HBinary(node, result, token, left, right);
847 static inline TokenKind
848 ToCompare(Expression *expr)
850 if (expr->isBinaryExpression()) {
851 BinaryExpression *b = expr->toBinaryExpression();
852 if (b->token() >= TOK_EQUALS && b->token() <= TOK_OR)
854 } else if (expr->isUnaryExpression()) {
855 UnaryExpression *u = expr->toUnaryExpression();
856 if (u->token() == TOK_NOT)
863 SemanticAnalysis::visitForTest(Expression *expr,
868 Local<Type> boolType(zone_, zone_->types()->getPrimitive(PrimitiveType_Bool));
870 TokenKind token = ToCompare(expr);
871 if (token == TOK_EOF || token == TOK_NOT) {
873 if (token == TOK_EOF)
876 hir = eval(expr->toUnaryExpression()->expression());
879 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
884 bool jumpOnTrue = (fallthrough == falseBranch) ^ (token == TOK_NOT);
885 Opcode op = jumpOnTrue ? OP_JT : OP_JF;
887 if (fallthrough == falseBranch)
888 __ j(op, trueBranch);
890 __ j(op, falseBranch);
894 BinaryExpression *bin = expr->toBinaryExpression();
895 if (token == TOK_AND || token == TOK_OR) {
897 //visitForLogicTest(expr, trueBranch, falseBranch, fallthrough);
901 HIR *left = eval(bin->left());
902 HIR *right = eval(bin->right());
906 HIR *hir = binary(bin, bin->token(), left, right);
909 if ((hir = coerce(hir, boolType, Coerce_Assign)) == NULL)
913 if (fallthrough == trueBranch)
914 __ j(OP_JF, falseBranch);
916 __ j(OP_JT, trueBranch);
920 SemanticAnalysis::lvalue(Expression *expr)
922 HIR *hir = eval(expr);
926 if (!hir->isLValue()) {
927 cc_.reportError(expr->pos(), Message_ExpectedLValue);
931 return static_cast<HLValue *>(hir);
935 SemanticAnalysis::eval(Expression *expr)
947 SemanticAnalysis::discharge(HIR *hir)
949 EmitHIR(zone_, emitter_, hir);