Keep high-level intermediate representation for IR::BINOPs.
[profile/ivi/qtdeclarative.git] / src / qml / qml / v4 / qv4compiler.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qv4compiler_p.h"
43 #include "qv4compiler_p_p.h"
44 #include "qv4program_p.h"
45 #include "qv4ir_p.h"
46 #include "qv4irbuilder_p.h"
47
48 #include <private/qqmlglobal_p.h>
49 #include <private/qqmljsast_p.h>
50 #include <private/qqmlaccessors_p.h>
51 #include <private/qqmljsengine_p.h>
52
53 QT_BEGIN_NAMESPACE
54
55 DEFINE_BOOL_CONFIG_OPTION(bindingsDump, QML_BINDINGS_DUMP)
56 DEFINE_BOOL_CONFIG_OPTION(qmlDisableOptimizer, QML_DISABLE_OPTIMIZER)
57 DEFINE_BOOL_CONFIG_OPTION(qmlExperimental, QML_EXPERIMENTAL)
58 DEFINE_BOOL_CONFIG_OPTION(qmlVerboseCompiler, QML_VERBOSE_COMPILER)
59 DEFINE_BOOL_CONFIG_OPTION(qmlBindingsTestEnv, QML_BINDINGS_TEST)
60
61 static bool qmlBindingsTest = false;
62 static bool qmlEnableV4 = true;
63
64 using namespace QQmlJS;
65 QV4CompilerPrivate::QV4CompilerPrivate()
66     : _function(0) , _block(0) , _discarded(false), registerCount(0)
67 {
68 }
69
70 //
71 // tracing
72 //
73 void QV4CompilerPrivate::trace(int line, int column)
74 {
75     bytecode.clear();
76
77     this->currentReg = _function->tempCount;
78     this->registerCount = qMax(this->registerCount, this->currentReg);
79
80     foreach (IR::BasicBlock *bb, _function->basicBlocks) {
81         if (! bb->isTerminated() && (bb->index + 1) < _function->basicBlocks.size())
82             bb->JUMP(_function->basicBlocks.at(bb->index + 1));
83     }
84
85     QVector<IR::BasicBlock *> blocks;
86     trace(&blocks);
87     currentBlockMask = 0x00000001;
88
89
90     for (int i = 0; !_discarded && i < blocks.size(); ++i) {
91         IR::BasicBlock *block = blocks.at(i);
92         IR::BasicBlock *next = i + 1 < blocks.size() ? blocks.at(i + 1) : 0;
93         if (IR::Stmt *terminator = block->terminator()) {
94             if (IR::CJump *cj = terminator->asCJump()) {
95                 if (cj->iffalse != next) {
96                     IR::Jump *jump = _function->pool->New<IR::Jump>();
97                     jump->init(cj->iffalse);
98                     block->statements.append(jump);
99                 }
100             } else if (IR::Jump *j = terminator->asJump()) {
101                 if (j->target == next) {
102                     block->statements.resize(block->statements.size() - 1);
103                 }
104             }
105         }
106
107         block->offset = bytecode.size();
108
109         if (bytecode.isEmpty()) {
110             if (qmlBindingsTest || bindingsDump()) {
111                 Instr::BindingId id;
112                 id.column = column;
113                 id.line = line;
114                 gen(id);
115             }
116
117             if (qmlBindingsTest) {
118                 QString str = expression->expression.asScript();
119                 QByteArray strdata((const char *)str.constData(), str.length() * sizeof(QChar));
120                 int offset = data.count();
121                 data += strdata;
122
123                 Instr::EnableV4Test test;
124                 test.reg = 0;
125                 test.offset = offset;
126                 test.length = str.length();
127                 gen(test);
128             }
129         }
130
131         bool usic = false;
132         int patchesCount = patches.count();
133         qSwap(usedSubscriptionIdsChanged, usic);
134
135         int blockopIndex = bytecode.size();
136         Instr::Block blockop;
137         blockop.block = currentBlockMask;
138         gen(blockop);
139
140         foreach (IR::Stmt *s, block->statements) {
141             if (! _discarded)
142                 s->accept(this);
143         }
144
145         qSwap(usedSubscriptionIdsChanged, usic);
146
147         if (usic) {
148             if (currentBlockMask == 0x80000000) {
149                 discard();
150                 return;
151             }
152             currentBlockMask <<= 1;
153         } else if (! _discarded) {
154             const int adjust = bytecode.remove(blockopIndex);
155             // Correct patches
156             for (int ii = patchesCount; ii < patches.count(); ++ii) 
157                 patches[ii].offset -= adjust;
158         }
159     }
160
161 #ifdef DEBUG_IR_STRUCTURE
162     IR::IRDump dump;
163     for (int i = 0; i < blocks.size(); ++i) {
164         dump.basicblock(blocks.at(i));
165     }
166 #endif
167
168
169     if (! _discarded) {
170         // back patching
171         foreach (const Patch &patch, patches) {
172             V4Instr &instr = bytecode[patch.offset];
173             int size = V4Instr::size(instructionType(&instr));
174             instr.branchop.offset = patch.block->offset - patch.offset - size;
175         }
176
177         patches.clear();
178     }
179 }
180
181 void QV4CompilerPrivate::trace(QVector<IR::BasicBlock *> *blocks)
182 {
183     for (int i = 0; i < _function->basicBlocks.size(); ++i) {
184         IR::BasicBlock *block = _function->basicBlocks.at(i);
185
186         while (! blocks->contains(block)) {
187             blocks->append(block);
188
189             if (IR::Stmt *terminator = block->terminator()) {
190                 if (IR::CJump *cj = terminator->asCJump())
191                     block = cj->iffalse;
192                 else if (IR::Jump *j = terminator->asJump())
193                     block = j->target;
194             }
195         }
196     }
197 }
198
199 void QV4CompilerPrivate::traceExpression(IR::Expr *e, quint8 r)
200 {
201     if (!e) {
202         discard();
203     } else {
204         qSwap(currentReg, r);
205         e->accept(this);
206         qSwap(currentReg, r);
207     }
208 }
209
210 //
211 // expressions
212 //
213 void QV4CompilerPrivate::visitConst(IR::Const *e)
214 {
215     switch (e->type) {
216     case IR::BoolType: {
217         Instr::LoadBool i;
218         i.reg = currentReg;
219         i.value = e->value;
220         gen(i);
221         } break;
222
223     case IR::IntType: {
224         Instr::LoadInt i;
225         i.reg = currentReg;
226         i.value = e->value;
227         gen(i);
228         } break;
229
230     case IR::RealType: {
231         Instr::LoadReal i;
232         i.reg = currentReg;
233         i.value = e->value;
234         gen(i);
235         } break;
236
237     default:
238         if (qmlVerboseCompiler())
239             qWarning() << Q_FUNC_INFO << "unexpected type";
240         discard();
241     }
242 }
243
244 void QV4CompilerPrivate::visitString(IR::String *e)
245 {
246     registerLiteralString(currentReg, e->value);
247 }
248
249 void QV4CompilerPrivate::visitName(IR::Name *e)
250 {
251     if (e->base) {
252         // fetch the object and store it in reg.
253         traceExpression(e->base, currentReg);
254     } else {
255         _subscribeName.clear();
256     }
257
258     if (e->storage == IR::Name::RootStorage) {
259
260         Instr::LoadRoot instr;
261         instr.reg = currentReg;
262         gen(instr);
263
264         if (e->symbol == IR::Name::IdObject) {
265             // The ID is a reference to the root object
266             return;
267         }
268
269     } else if (e->storage == IR::Name::ScopeStorage) {
270
271         Instr::LoadScope instr;
272         instr.reg = currentReg;
273         gen(instr);
274
275         _subscribeName << contextName();
276
277     } else if (e->storage == IR::Name::IdStorage) {
278
279         Instr::LoadId instr;
280         instr.reg = currentReg;
281         instr.index = e->idObject->idIndex;
282         gen(instr);
283
284         _subscribeName << QLatin1String("$$$ID_") + *e->id;
285
286         if (blockNeedsSubscription(_subscribeName)) {
287             Instr::SubscribeId sub;
288             sub.reg = currentReg;
289             sub.offset = subscriptionIndex(_subscribeName);
290             sub.index = instr.index;
291             gen(sub);
292         }
293
294         return;
295     } else {
296         // No action needed
297     }
298
299     switch (e->symbol) {
300     case IR::Name::Unbound: 
301     case IR::Name::IdObject: 
302     case IR::Name::Slot:
303     case IR::Name::Object: {
304         Q_ASSERT(!"Unreachable");
305         discard();
306     } break;
307
308     case IR::Name::AttachType: {
309         _subscribeName << *e->id;
310
311         Instr::LoadAttached attached;
312         attached.output = currentReg;
313         attached.reg = currentReg;
314         attached.exceptionId = exceptionId(e->line, e->column);
315         if (e->declarativeType->attachedPropertiesId() == -1)
316             discard();
317         attached.id = e->declarativeType->attachedPropertiesId();
318         gen(attached);
319     } break;
320
321     case IR::Name::Property: {
322         _subscribeName << *e->id;
323
324         if (e->property->coreIndex == -1) {
325             QMetaProperty prop;
326             e->property->load(prop, QQmlEnginePrivate::get(engine));
327         }
328
329         const int propTy = e->property->propType;
330         QQmlRegisterType regType;
331
332         switch (propTy) {
333         case QMetaType::QReal:
334             regType = QRealType;
335             break;
336         case QMetaType::Bool:
337             regType = BoolType;
338             break;
339         case QMetaType::Int:
340             regType = IntType;
341             break;
342         case QMetaType::QString:
343             regType = QStringType;
344             break;
345         case QMetaType::QUrl:
346             regType = QUrlType;
347             break;
348         case QMetaType::QColor:
349             regType = QColorType;
350             break;
351
352         default:
353             if (propTy == QQmlMetaType::QQuickAnchorLineMetaTypeId()) {
354                 regType = PODValueType;
355             } else if (QQmlMetaType::isQObject(propTy)) {
356                 regType = QObjectStarType;
357             } else {
358                 if (qmlVerboseCompiler())
359                     qWarning() << "Discard unsupported property type:" << QMetaType::typeName(propTy);
360                 discard(); // Unsupported type
361                 return;
362             }
363
364             break;
365         } // switch
366
367         if (e->property->hasAccessors()) {
368             Instr::FetchAndSubscribe fetch;
369             fetch.reg = currentReg;
370             fetch.subscription = subscriptionIndex(_subscribeName);
371             fetch.exceptionId = exceptionId(e->line, e->column);
372             fetch.valueType = regType;
373             fetch.property = *e->property;
374             gen(fetch);
375         } else {
376             if (blockNeedsSubscription(_subscribeName) && e->property->notifyIndex != -1) {
377                 Instr::Subscribe sub;
378                 sub.reg = currentReg;
379                 sub.offset = subscriptionIndex(_subscribeName);
380                 sub.index = e->property->notifyIndex;
381                 gen(sub);
382             }
383
384             Instr::Fetch fetch;
385             fetch.reg = currentReg;
386             fetch.index = e->property->coreIndex;
387             fetch.exceptionId = exceptionId(e->line, e->column);
388             fetch.valueType = regType;
389             gen(fetch);
390         }
391
392     } break;
393     } // switch
394 }
395
396 void QV4CompilerPrivate::visitTemp(IR::Temp *e)
397 {
398     if (currentReg != e->index) {
399         Instr::Copy i;
400         i.reg = currentReg;
401         i.src = e->index;
402         gen(i);
403     }
404 }
405
406 void QV4CompilerPrivate::visitUnop(IR::Unop *e)
407 {
408     quint8 src = currentReg;
409     
410     if (IR::Temp *temp = e->expr->asTemp()) {
411         src = temp->index;
412     } else {
413         traceExpression(e->expr, src);
414     }
415
416     switch (e->op) {
417     case IR::OpInvalid:
418         Q_ASSERT(!"unreachable");
419         break;
420
421     case IR::OpIfTrue:
422         convertToBool(e->expr, src);
423         if (src != currentReg) {
424             Instr::Copy i;
425             i.reg = currentReg;
426             i.src = src;
427             gen(i);
428         }
429         break;
430
431     case IR::OpNot: {
432         Instr::UnaryNot i;
433         convertToBool(e->expr, src);
434         i.output = currentReg;
435         i.src = src;
436         gen(i);
437         } break;
438
439     case IR::OpUMinus:
440         if (e->expr->type == IR::RealType) {
441             Instr::UnaryMinusReal i;
442             i.output = currentReg;
443             i.src = src;
444             gen(i);
445         } else if (e->expr->type == IR::IntType) {
446             convertToReal(e->expr, currentReg);
447             Instr::UnaryMinusReal i;
448             i.output = currentReg;
449             i.src = src;
450             gen(i);
451         } else {
452             discard();
453         }
454         break;
455
456     case IR::OpUPlus:
457         if (e->expr->type == IR::RealType) {
458             Instr::UnaryPlusReal i;
459             i.output = currentReg;
460             i.src = src;
461             gen(i);
462         } else if (e->expr->type == IR::IntType) {
463             convertToReal(e->expr, currentReg);
464             Instr::UnaryPlusReal i;
465             i.output = currentReg;
466             i.src = src;
467             gen(i);
468         } else {
469             discard();
470         }
471         break;
472
473     case IR::OpCompl:
474         // TODO
475         discard();
476         break;
477
478     case IR::OpBitAnd:
479     case IR::OpBitOr:
480     case IR::OpBitXor:
481     case IR::OpAdd:
482     case IR::OpSub:
483     case IR::OpMul:
484     case IR::OpDiv:
485     case IR::OpMod:
486     case IR::OpLShift:
487     case IR::OpRShift:
488     case IR::OpURShift:
489     case IR::OpGt:
490     case IR::OpLt:
491     case IR::OpGe:
492     case IR::OpLe:
493     case IR::OpEqual:
494     case IR::OpNotEqual:
495     case IR::OpStrictEqual:
496     case IR::OpStrictNotEqual:
497     case IR::OpAnd:
498     case IR::OpOr:
499         Q_ASSERT(!"unreachable");
500         break;
501     } // switch
502 }
503
504 void QV4CompilerPrivate::convertToReal(IR::Expr *expr, int reg)
505 {
506     if (expr->type == IR::RealType)
507         return;
508
509     switch (expr->type) {
510     case IR::BoolType: {
511         Instr::ConvertBoolToReal i;
512         i.output = i.src = reg;
513         gen(i);
514         } break;
515
516     case IR::IntType: {
517         Instr::ConvertIntToReal i;
518         i.output = i.src = reg;
519         gen(i);
520         } break;
521
522     case IR::RealType:
523         // nothing to do
524         return;
525
526     default:
527         discard();
528         break;
529     } // switch
530 }
531
532 void QV4CompilerPrivate::convertToInt(IR::Expr *expr, int reg)
533 {
534     if (expr->type == IR::IntType)
535         return;
536
537     switch (expr->type) {
538     case IR::BoolType: {
539         Instr::ConvertBoolToInt i;
540         i.output = i.src = reg;
541         gen(i);
542         } break;
543
544     case IR::IntType:
545         // nothing to do
546         return;
547
548     case IR::RealType: {
549         Instr::ConvertRealToInt i;
550         i.output = i.src = reg;
551         gen(i);
552         } break;
553
554     default:
555         discard();
556         break;
557     } // switch
558 }
559
560 void QV4CompilerPrivate::convertToBool(IR::Expr *expr, int reg)
561 {
562     if (expr->type == IR::BoolType)
563         return;
564
565     switch (expr->type) {
566     case IR::BoolType:
567         // nothing to do
568         break;
569
570     case IR::IntType: {
571         Instr::ConvertIntToBool i;
572         i.output = i.src = reg;
573         gen(i);
574         } break;
575
576     case IR::RealType: {
577         Instr::ConvertRealToBool i;
578         i.output = i.src = reg;
579         gen(i);
580         } return;
581
582     case IR::StringType: {
583         Instr::ConvertStringToBool i;
584         i.output = i.src = reg;
585         gen(i);
586         } return;
587
588     case IR::ColorType: {
589         Instr::ConvertColorToBool i;
590         i.output = i.src = reg;
591         gen(i);
592         } return;
593
594     default:
595         discard();
596         break;
597     } // switch
598 }
599
600 quint8 QV4CompilerPrivate::instructionOpcode(IR::Binop *e)
601 {
602     switch (e->op) {
603     case IR::OpInvalid:
604         return V4Instr::Noop;
605
606     case IR::OpIfTrue:
607     case IR::OpNot:
608     case IR::OpUMinus:
609     case IR::OpUPlus:
610     case IR::OpCompl:
611         return V4Instr::Noop;
612
613     case IR::OpBitAnd:
614         return V4Instr::BitAndInt;
615
616     case IR::OpBitOr:
617         return V4Instr::BitOrInt;
618
619     case IR::OpBitXor:
620         return V4Instr::BitXorInt;
621
622     case IR::OpAdd:
623         if (e->type == IR::StringType)
624             return V4Instr::AddString;
625         return V4Instr::AddReal;
626
627     case IR::OpSub:
628         return V4Instr::SubReal;
629
630     case IR::OpMul:
631         return V4Instr::MulReal;
632
633     case IR::OpDiv:
634         return V4Instr::DivReal;
635
636     case IR::OpMod:
637         return V4Instr::ModReal;
638
639     case IR::OpLShift:
640         return V4Instr::LShiftInt;
641
642     case IR::OpRShift:
643         return V4Instr::RShiftInt;
644
645     case IR::OpURShift:
646         return V4Instr::URShiftInt;
647
648     case IR::OpGt:
649         if (e->left->type == IR::StringType)
650             return V4Instr::GtString;
651         return V4Instr::GtReal;
652
653     case IR::OpLt:
654         if (e->left->type == IR::StringType)
655             return V4Instr::LtString;
656         return V4Instr::LtReal;
657
658     case IR::OpGe:
659         if (e->left->type == IR::StringType)
660             return V4Instr::GeString;
661         return V4Instr::GeReal;
662
663     case IR::OpLe:
664         if (e->left->type == IR::StringType)
665             return V4Instr::LeString;
666         return V4Instr::LeReal;
667
668     case IR::OpEqual:
669         if (e->left->type == IR::StringType)
670             return V4Instr::EqualString;
671         return V4Instr::EqualReal;
672
673     case IR::OpNotEqual:
674         if (e->left->type == IR::StringType)
675             return V4Instr::NotEqualString;
676         return V4Instr::NotEqualReal;
677
678     case IR::OpStrictEqual:
679         if (e->left->type == IR::StringType)
680             return V4Instr::StrictEqualString;
681         return V4Instr::StrictEqualReal;
682
683     case IR::OpStrictNotEqual:
684         if (e->left->type == IR::StringType)
685             return V4Instr::StrictNotEqualString;
686         return V4Instr::StrictNotEqualReal;
687
688     case IR::OpAnd:
689     case IR::OpOr:
690         return V4Instr::Noop;
691
692     } // switch
693
694     return V4Instr::Noop;
695 }
696
697 void QV4CompilerPrivate::visitBinop(IR::Binop *e)
698 {
699     if (e->type == IR::InvalidType) {
700         discard();
701         return;
702     }
703
704     int left = currentReg;
705     int right = currentReg + 1; 
706
707     traceExpression(e->left, left);
708     traceExpression(e->right, right);
709
710     // At this point it is possible that the type of the
711     // subexpressions is different. This can happen because
712     // we keep BINOP expressions in HIR.
713
714     switch (e->op) {
715     case IR::OpInvalid:
716         discard();
717         break;
718
719     // unary
720     case IR::OpIfTrue:
721     case IR::OpNot:
722     case IR::OpUMinus:
723     case IR::OpUPlus:
724     case IR::OpCompl:
725         discard();
726         break;
727
728     case IR::OpBitAnd:
729     case IR::OpBitOr:
730     case IR::OpBitXor:
731     case IR::OpLShift:
732     case IR::OpRShift:
733     case IR::OpURShift:
734         convertToInt(e->left, left);
735         convertToInt(e->right, right);
736         break;
737
738     case IR::OpAdd:
739         if (e->type != IR::StringType) {
740             convertToReal(e->left, left);
741             convertToReal(e->right, right);
742         }
743         break;
744
745     case IR::OpSub:
746     case IR::OpMul:
747     case IR::OpDiv:
748     case IR::OpMod:
749         convertToReal(e->left, left);
750         convertToReal(e->right, right);
751         break;
752
753     case IR::OpGt:
754     case IR::OpLt:
755     case IR::OpGe:
756     case IR::OpLe:
757     case IR::OpEqual:
758     case IR::OpNotEqual:
759     case IR::OpStrictEqual:
760     case IR::OpStrictNotEqual:
761         if (e->left->type != IR::StringType) {
762             convertToReal(e->left, left);
763             convertToReal(e->right, right);
764         }
765         break;
766
767     case IR::OpAnd:
768     case IR::OpOr:
769         discard(); // ### unreachable
770         break;
771     } // switch
772
773     const quint8 opcode = instructionOpcode(e);
774     if (opcode != V4Instr::Noop) {
775         V4Instr instr;
776         instr.binaryop.output = currentReg;
777         instr.binaryop.left = left;
778         instr.binaryop.right = right;
779         gen(static_cast<V4Instr::Type>(opcode), instr);
780     }
781 }
782
783 void QV4CompilerPrivate::visitCall(IR::Call *call)
784 {
785     if (IR::Name *name = call->base->asName()) {
786         IR::Expr *arg = call->onlyArgument();
787         if (arg != 0 && arg->type == IR::RealType) {
788             traceExpression(arg, currentReg);
789
790             switch (name->builtin) {
791             case IR::NoBuiltinSymbol:
792                 break;
793
794             case IR::MathSinBultinFunction: {
795                 Instr::MathSinReal i;
796                 i.output = i.src = currentReg;
797                 gen(i);
798                 } return;
799
800             case IR::MathCosBultinFunction: {
801                 Instr::MathCosReal i;
802                 i.output = i.src = currentReg;
803                 gen(i);
804                 } return;
805
806             case IR::MathRoundBultinFunction: {
807                 Instr::MathRoundReal i;
808                 i.output = i.src = currentReg;
809                 gen(i);
810                 } return;
811
812             case IR::MathFloorBultinFunction: {
813                 Instr::MathFloorReal i;
814                 i.output = i.src = currentReg;
815                 gen(i);
816                 } return;
817
818             case IR::MathPIBuiltinConstant:
819                 break;
820             } // switch
821         }
822     }
823
824     if (qmlVerboseCompiler())
825         qWarning() << "TODO:" << Q_FUNC_INFO << __LINE__;
826     discard();
827 }
828
829
830 //
831 // statements
832 //
833 void QV4CompilerPrivate::visitExp(IR::Exp *s)
834 {
835     traceExpression(s->expr, currentReg);
836 }
837
838 void QV4CompilerPrivate::visitMove(IR::Move *s)
839 {
840     IR::Temp *target = s->target->asTemp();
841     Q_ASSERT(target != 0);
842
843     quint8 dest = target->index;
844
845     if (target->type != s->source->type) {
846         quint8 src = dest;
847
848         if (IR::Temp *t = s->source->asTemp()) 
849             src = t->index;
850         else
851             traceExpression(s->source, dest);
852
853         V4Instr::Type opcode = V4Instr::Noop;
854         IR::Type targetTy = s->target->type;
855         IR::Type sourceTy = s->source->type;
856
857         if (sourceTy == IR::UrlType) {
858             switch (targetTy) {
859             case IR::BoolType:
860             case IR::StringType:
861                 // nothing to do. V4 will generate optimized
862                 // url-to-xxx conversions.
863                 break;
864             default: {
865                 // generate a UrlToString conversion and fix
866                 // the type of the source expression.
867                 V4Instr conv;
868                 conv.unaryop.output = V4Instr::ConvertUrlToString;
869                 conv.unaryop.src = src;
870                 gen(opcode, conv);
871
872                 sourceTy = IR::StringType;
873                 break;
874             }
875             } // switch
876         }
877
878         if (targetTy == IR::BoolType) {
879             switch (sourceTy) {
880             case IR::IntType: opcode = V4Instr::ConvertIntToBool; break;
881             case IR::RealType: opcode = V4Instr::ConvertRealToBool; break;
882             case IR::StringType: opcode = V4Instr::ConvertStringToBool; break;
883             case IR::UrlType: opcode = V4Instr::ConvertUrlToBool; break;
884             case IR::ColorType: opcode = V4Instr::ConvertColorToBool; break;
885             default: break;
886             } // switch
887         } else if (targetTy == IR::IntType) {
888             switch (sourceTy) {
889             case IR::BoolType: opcode = V4Instr::ConvertBoolToInt; break;
890             case IR::RealType: {
891                 if (s->isMoveForReturn)
892                     opcode = V4Instr::MathRoundReal;
893                 else
894                     opcode = V4Instr::ConvertRealToInt;
895                 break;
896             }
897             case IR::StringType: opcode = V4Instr::ConvertStringToInt; break;
898             default: break;
899             } // switch
900         } else if (targetTy == IR::RealType) {
901             switch (sourceTy) {
902             case IR::BoolType: opcode = V4Instr::ConvertBoolToReal; break;
903             case IR::IntType: opcode = V4Instr::ConvertIntToReal; break;
904             case IR::StringType: opcode = V4Instr::ConvertStringToReal; break;
905             default: break;
906             } // switch
907         } else if (targetTy == IR::StringType) {
908             switch (sourceTy) {
909             case IR::BoolType: opcode = V4Instr::ConvertBoolToString; break;
910             case IR::IntType:  opcode = V4Instr::ConvertIntToString; break;
911             case IR::RealType: opcode = V4Instr::ConvertRealToString; break;
912             case IR::UrlType: opcode = V4Instr::ConvertUrlToString; break;
913             case IR::ColorType: opcode = V4Instr::ConvertColorToString; break;
914             default: break;
915             } // switch
916         } else if (targetTy == IR::UrlType) {
917             V4Instr convToString;
918             convToString.unaryop.output = dest;
919             convToString.unaryop.src = src;
920
921             // try to convert the source expression to a string.
922             switch (sourceTy) {
923             case IR::BoolType: gen(V4Instr::ConvertBoolToString, convToString); sourceTy = IR::StringType; break;
924             case IR::IntType:  gen(V4Instr::ConvertIntToString,  convToString); sourceTy = IR::StringType; break;
925             case IR::RealType: gen(V4Instr::ConvertRealToString, convToString); sourceTy = IR::StringType; break;
926             case IR::ColorType: gen(V4Instr::ConvertColorToString, convToString); sourceTy = IR::StringType; break;
927             default: break;
928             } // switch
929
930             if (sourceTy == IR::StringType)
931                 opcode = V4Instr::ConvertStringToUrl;
932         } else if (targetTy == IR::ColorType) {
933             switch (sourceTy) {
934             case IR::StringType: opcode = V4Instr::ConvertStringToColor; break;
935             default: break;
936             } // switch
937         }
938         if (opcode != V4Instr::Noop) {
939             V4Instr conv;
940             conv.unaryop.output = dest;
941             conv.unaryop.src = src;
942             gen(opcode, conv);
943
944             if (s->isMoveForReturn && opcode == V4Instr::ConvertStringToUrl) {
945                 V4Instr resolveUrl;
946                 resolveUrl.unaryop.output = dest;
947                 resolveUrl.unaryop.src = dest;
948                 gen(V4Instr::ResolveUrl, resolveUrl);
949             }
950         } else {
951             discard();
952         }
953     } else {
954         traceExpression(s->source, dest);
955     }
956 }
957
958 void QV4CompilerPrivate::visitJump(IR::Jump *s)
959 {
960     patches.append(Patch(s->target, bytecode.size()));
961
962     Instr::Branch i;
963     i.offset = 0; // ### backpatch
964     gen(i);
965 }
966
967 void QV4CompilerPrivate::visitCJump(IR::CJump *s)
968 {
969     traceExpression(s->cond, currentReg);
970
971     patches.append(Patch(s->iftrue, bytecode.size()));
972
973     Instr::BranchTrue i;
974     i.reg = currentReg;
975     i.offset = 0; // ### backpatch
976     gen(i);
977 }
978
979 void QV4CompilerPrivate::visitRet(IR::Ret *s)
980 {
981     Q_ASSERT(s->expr != 0);
982
983     int storeReg = currentReg;
984
985     if (IR::Temp *temp = s->expr->asTemp()) {
986         storeReg = temp->index;
987     } else {
988         traceExpression(s->expr, storeReg);
989     }
990
991     if (qmlBindingsTest) {
992         Instr::TestV4Store test;
993         test.reg = storeReg;
994         switch (s->type) {
995         case IR::StringType:
996             test.regType = QMetaType::QString;
997             break;
998         case IR::UrlType:
999             test.regType = QMetaType::QUrl;
1000             break;
1001         case IR::ColorType:
1002             test.regType = QMetaType::QColor;
1003             break;
1004         case IR::SGAnchorLineType:
1005             test.regType = QQmlMetaType::QQuickAnchorLineMetaTypeId();
1006             break;
1007         case IR::ObjectType:
1008             test.regType = QMetaType::QObjectStar;
1009             break;
1010         case IR::BoolType:
1011             test.regType = QMetaType::Bool;
1012             break;
1013         case IR::IntType:
1014             test.regType = QMetaType::Int;
1015             break;
1016         case IR::RealType:
1017             test.regType = QMetaType::QReal;
1018             break;
1019         default:
1020             discard();
1021             return;
1022         }
1023         gen(test);
1024     }
1025
1026     Instr::Store store;
1027     store.output = 0;
1028     store.index = expression->property->index;
1029     store.reg = storeReg;
1030     store.exceptionId = exceptionId(s->line, s->column);
1031     gen(store);
1032 }
1033
1034 void QV4Compiler::dump(const QByteArray &programData)
1035 {
1036     const QV4Program *program = (const QV4Program *)programData.constData();
1037
1038     qWarning() << "Program.bindings:" << program->bindings;
1039     qWarning() << "Program.dataLength:" << program->dataLength;
1040     qWarning() << "Program.subscriptions:" << program->subscriptions;
1041     qWarning() << "Program.indentifiers:" << program->identifiers;
1042
1043     const int programSize = program->instructionCount;
1044     const char *start = program->instructions();
1045     const char *end = start + programSize;
1046     Bytecode bc;
1047     bc.dump(start, end);
1048 }
1049
1050 /*!
1051 Clear the state associated with attempting to compile a specific binding.
1052 This does not clear the global "committed binding" states.
1053 */
1054 void QV4CompilerPrivate::resetInstanceState()
1055 {
1056     data = committed.data;
1057     exceptions = committed.exceptions;
1058     usedSubscriptionIds.clear();
1059     subscriptionIds = committed.subscriptionIds;
1060     registeredStrings = committed.registeredStrings;
1061     bytecode.clear();
1062     patches.clear();
1063     pool.clear();
1064     currentReg = 0;
1065 }
1066
1067 /*!
1068 Mark the last compile as successful, and add it to the "committed data"
1069 section.
1070
1071 Returns the index for the committed binding.
1072 */
1073 int QV4CompilerPrivate::commitCompile()
1074 {
1075     int rv = committed.count();
1076     committed.offsets << committed.bytecode.count();
1077     committed.dependencies << usedSubscriptionIds;
1078     committed.bytecode.append(bytecode.constData(), bytecode.size());
1079     committed.data = data;
1080     committed.exceptions = exceptions;
1081     committed.subscriptionIds = subscriptionIds;
1082     committed.registeredStrings = registeredStrings;
1083     return rv;
1084 }
1085
1086 bool QV4CompilerPrivate::compile(QQmlJS::AST::Node *node)
1087 {
1088     resetInstanceState();
1089
1090     if (expression->property->type == -1)
1091         return false;
1092
1093     AST::SourceLocation location;
1094     if (AST::ExpressionNode *astExpression = node->expressionCast()) {
1095         location = astExpression->firstSourceLocation();
1096     } else if (AST::Statement *astStatement = node->statementCast()) {
1097         if (AST::Block *block = AST::cast<AST::Block *>(astStatement))
1098             location = block->lbraceToken;
1099         else if (AST::IfStatement *ifStmt = AST::cast<AST::IfStatement *>(astStatement))
1100             location = ifStmt->ifToken;
1101         else
1102             return false;
1103     } else {
1104         return false;
1105     }
1106
1107     IR::Function thisFunction(&pool), *function = &thisFunction;
1108
1109     QV4IRBuilder irBuilder(expression, engine);
1110     if (!irBuilder(function, node))
1111         return false;
1112
1113     bool discarded = false;
1114     qSwap(_discarded, discarded);
1115     qSwap(_function, function);
1116     trace(location.startLine, location.startColumn);
1117     qSwap(_function, function);
1118     qSwap(_discarded, discarded);
1119
1120     if (qmlVerboseCompiler()) {
1121         QTextStream qerr(stderr, QIODevice::WriteOnly);
1122         if (discarded)
1123             qerr << "======== TODO ====== " << endl;
1124         else 
1125             qerr << "==================== " << endl;
1126         qerr << "\tline: " << location.startLine
1127              << "\tcolumn: " << location.startColumn
1128              << endl;
1129         foreach (IR::BasicBlock *bb, function->basicBlocks)
1130             bb->dump(qerr);
1131         qerr << endl;
1132     }
1133
1134     if (discarded || subscriptionIds.count() > 0xFFFF || registeredStrings.count() > 0xFFFF || registerCount > 31)
1135         return false;
1136
1137     return true;
1138 }
1139
1140 // Returns a reg
1141 int QV4CompilerPrivate::registerLiteralString(quint8 reg, const QStringRef &str)
1142 {
1143     // ### string cleanup
1144
1145     QByteArray strdata((const char *)str.constData(), str.length() * sizeof(QChar));
1146     int offset = data.count();
1147     data += strdata;
1148
1149     Instr::LoadString string;
1150     string.reg = reg;
1151     string.offset = offset;
1152     string.length = str.length();
1153     gen(string);
1154
1155     return reg;
1156 }
1157
1158 // Returns an identifier offset
1159 int QV4CompilerPrivate::registerString(const QString &string)
1160 {
1161     Q_ASSERT(!string.isEmpty());
1162
1163     QPair<int, int> *iter = registeredStrings.value(string);
1164
1165     if (!iter) {
1166         quint32 len = string.length();
1167         QByteArray lendata((const char *)&len, sizeof(quint32));
1168         QByteArray strdata((const char *)string.constData(), string.length() * sizeof(QChar));
1169         strdata.prepend(lendata);
1170         int rv = data.count();
1171         data += strdata;
1172
1173         iter = &registeredStrings[string];
1174         *iter = qMakePair(registeredStrings.count(), rv);
1175     } 
1176
1177     Instr::InitString reg;
1178     reg.offset = iter->first;
1179     reg.dataIdx = iter->second;
1180     gen(reg);
1181     return reg.offset;
1182 }
1183
1184 /*!
1185 Returns true if the current expression has not already subscribed to \a sub in currentBlockMask.
1186 */
1187 bool QV4CompilerPrivate::blockNeedsSubscription(const QStringList &sub)
1188 {
1189     QString str = sub.join(QLatin1String("."));
1190
1191     int *iter = subscriptionIds.value(str);
1192     if (!iter)
1193         return true;
1194
1195     quint32 *uiter = usedSubscriptionIds.value(*iter);
1196     if (!uiter)
1197         return true;
1198     else
1199         return !(*uiter & currentBlockMask);
1200 }
1201
1202 int QV4CompilerPrivate::subscriptionIndex(const QStringList &sub)
1203 {
1204     QString str = sub.join(QLatin1String("."));
1205     int *iter = subscriptionIds.value(str);
1206     if (!iter) {
1207         int count = subscriptionIds.count();
1208         iter = &subscriptionIds[str];
1209         *iter = count;
1210     }
1211     quint32 &u = usedSubscriptionIds[*iter];
1212     if (!(u & currentBlockMask)) {
1213         u |= currentBlockMask;
1214         usedSubscriptionIdsChanged = true;
1215     }
1216     return *iter;
1217 }
1218
1219 quint32 QV4CompilerPrivate::subscriptionBlockMask(const QStringList &sub)
1220 {
1221     QString str = sub.join(QLatin1String("."));
1222
1223     int *iter = subscriptionIds.value(str);
1224     Q_ASSERT(iter != 0);
1225
1226     quint32 *uiter = usedSubscriptionIds.value(*iter);
1227     Q_ASSERT(uiter != 0);
1228
1229     return *uiter;
1230 }
1231
1232 quint8 QV4CompilerPrivate::exceptionId(quint32 line, quint32 column)
1233 {
1234     quint8 rv = 0xFF;
1235     if (exceptions.count() < 0xFF) {
1236         rv = (quint8)exceptions.count();
1237         quint64 e = line;
1238         e <<= 32;
1239         e |= column;
1240         exceptions.append(e);
1241     }
1242     return rv;
1243 }
1244
1245 quint8 QV4CompilerPrivate::exceptionId(QQmlJS::AST::ExpressionNode *n)
1246 {
1247     quint8 rv = 0xFF;
1248     if (n && exceptions.count() < 0xFF) {
1249         QQmlJS::AST::SourceLocation l = n->firstSourceLocation();
1250         rv = exceptionId(l.startLine, l.startColumn);
1251     }
1252     return rv;
1253 }
1254
1255 QV4Compiler::QV4Compiler()
1256 : d(new QV4CompilerPrivate)
1257 {
1258     qmlBindingsTest |= qmlBindingsTestEnv();
1259 }
1260
1261 QV4Compiler::~QV4Compiler()
1262 {
1263     delete d; d = 0;
1264 }
1265
1266 /* 
1267 Returns true if any bindings were compiled.
1268 */
1269 bool QV4Compiler::isValid() const
1270 {
1271     return !d->committed.bytecode.isEmpty();
1272 }
1273
1274 /* 
1275 -1 on failure, otherwise the binding index to use.
1276 */
1277 int QV4Compiler::compile(const Expression &expression, QQmlEnginePrivate *engine)
1278 {
1279     if (!expression.expression.asAST()) return false;
1280
1281     if (!qmlExperimental() && expression.property->isValueTypeSubProperty)
1282         return -1;
1283
1284     if (qmlDisableOptimizer() || !qmlEnableV4)
1285         return -1;
1286
1287     d->expression = &expression;
1288     d->engine = engine;
1289
1290     if (d->compile(expression.expression.asAST())) {
1291         return d->commitCompile();
1292     } else {
1293         return -1;
1294     }
1295 }
1296
1297 QByteArray QV4CompilerPrivate::buildSignalTable() const
1298 {
1299     QHash<int, QList<QPair<int, quint32> > > table;
1300
1301     for (int ii = 0; ii < committed.count(); ++ii) {
1302         const QQmlAssociationList<int, quint32> &deps = committed.dependencies.at(ii);
1303         for (QQmlAssociationList<int, quint32>::const_iterator iter = deps.begin(); iter != deps.end(); ++iter)
1304             table[iter->first].append(qMakePair(ii, iter->second));
1305     }
1306
1307     QVector<quint32> header;
1308     QVector<quint32> data;
1309     for (int ii = 0; ii < committed.subscriptionIds.count(); ++ii) {
1310         header.append(committed.subscriptionIds.count() + data.count());
1311         const QList<QPair<int, quint32> > &bindings = table[ii];
1312         data.append(bindings.count());
1313         for (int jj = 0; jj < bindings.count(); ++jj) {
1314             data.append(bindings.at(jj).first);
1315             data.append(bindings.at(jj).second);
1316         }
1317     }
1318     header << data;
1319
1320     return QByteArray((const char *)header.constData(), header.count() * sizeof(quint32));
1321 }
1322
1323 QByteArray QV4CompilerPrivate::buildExceptionData() const
1324 {
1325     QByteArray rv;
1326     rv.resize(committed.exceptions.count() * sizeof(quint64));
1327     ::memcpy(rv.data(), committed.exceptions.constData(), rv.size());
1328     return rv;
1329 }
1330
1331 /* 
1332 Returns the compiled program.
1333 */
1334 QByteArray QV4Compiler::program() const
1335 {
1336     QByteArray programData;
1337
1338     if (isValid()) {
1339         QV4Program prog;
1340         prog.bindings = d->committed.count();
1341
1342         Bytecode bc;
1343         QV4CompilerPrivate::Instr::Jump jump;
1344         jump.reg = -1;
1345
1346         for (int ii = 0; ii < d->committed.count(); ++ii) {
1347             jump.count = d->committed.count() - ii - 1;
1348             jump.count*= V4InstrMeta<V4Instr::Jump>::Size;
1349             jump.count+= d->committed.offsets.at(ii);
1350             bc.append(jump);
1351         }
1352
1353
1354         QByteArray bytecode;
1355         bytecode.reserve(bc.size() + d->committed.bytecode.size());
1356         bytecode.append(bc.constData(), bc.size());
1357         bytecode.append(d->committed.bytecode.constData(), d->committed.bytecode.size());
1358
1359         QByteArray data = d->committed.data;
1360         while (data.count() % 4) data.append('\0');
1361         prog.signalTableOffset = data.count();
1362         data += d->buildSignalTable();
1363         while (data.count() % 4) data.append('\0');
1364         prog.exceptionDataOffset = data.count();
1365         data += d->buildExceptionData();
1366
1367         prog.dataLength = 4 * ((data.size() + 3) / 4);
1368         prog.subscriptions = d->committed.subscriptionIds.count();
1369         prog.identifiers = d->committed.registeredStrings.count();
1370         prog.instructionCount = bytecode.count();
1371         int size = sizeof(QV4Program) + bytecode.count();
1372         size += prog.dataLength;
1373
1374         programData.resize(size);
1375         memcpy(programData.data(), &prog, sizeof(QV4Program));
1376         if (prog.dataLength)
1377             memcpy((char *)((QV4Program *)programData.data())->data(), data.constData(), 
1378                    data.size());
1379         memcpy((char *)((QV4Program *)programData.data())->instructions(), bytecode.constData(),
1380                bytecode.count());
1381     } 
1382
1383     if (bindingsDump()) {
1384         qWarning().nospace() << "Subscription slots:";
1385
1386         for (QQmlAssociationList<QString, int>::ConstIterator iter = d->committed.subscriptionIds.begin();
1387                 iter != d->committed.subscriptionIds.end();
1388                 ++iter) {
1389             qWarning().nospace() << "    " << iter->first << "\t-> " << iter->second;
1390         }
1391
1392         QV4Compiler::dump(programData);
1393     }
1394
1395     return programData;
1396 }
1397
1398 void QV4Compiler::enableBindingsTest(bool e)
1399 {
1400     if (e)
1401         qmlBindingsTest = true;
1402     else 
1403         qmlBindingsTest = qmlBindingsTestEnv();
1404 }
1405
1406 void QV4Compiler::enableV4(bool e)
1407 {
1408     qmlEnableV4 = e;
1409 }
1410
1411 QT_END_NAMESPACE