xref: /sqlite-3.40.0/src/expr.c (revision c5e56b34)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 */
15 #include "sqliteInt.h"
16 
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20 
21 /*
22 ** Return the affinity character for a single column of a table.
23 */
24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){
25   assert( iCol<pTab->nCol );
26   return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
27 }
28 
29 /*
30 ** Return the 'affinity' of the expression pExpr if any.
31 **
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
36 **
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
39 **
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
44 */
45 char sqlite3ExprAffinity(Expr *pExpr){
46   int op;
47   pExpr = sqlite3ExprSkipCollate(pExpr);
48   if( pExpr->flags & EP_Generic ) return 0;
49   op = pExpr->op;
50   if( op==TK_SELECT ){
51     assert( pExpr->flags&EP_xIsSelect );
52     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
53   }
54   if( op==TK_REGISTER ) op = pExpr->op2;
55 #ifndef SQLITE_OMIT_CAST
56   if( op==TK_CAST ){
57     assert( !ExprHasProperty(pExpr, EP_IntValue) );
58     return sqlite3AffinityType(pExpr->u.zToken, 0);
59   }
60 #endif
61   if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
62     return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
63   }
64   if( op==TK_SELECT_COLUMN ){
65     assert( pExpr->pLeft->flags&EP_xIsSelect );
66     return sqlite3ExprAffinity(
67         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
68     );
69   }
70   return pExpr->affinity;
71 }
72 
73 /*
74 ** Set the collating sequence for expression pExpr to be the collating
75 ** sequence named by pToken.   Return a pointer to a new Expr node that
76 ** implements the COLLATE operator.
77 **
78 ** If a memory allocation error occurs, that fact is recorded in pParse->db
79 ** and the pExpr parameter is returned unchanged.
80 */
81 Expr *sqlite3ExprAddCollateToken(
82   Parse *pParse,           /* Parsing context */
83   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
84   const Token *pCollName,  /* Name of collating sequence */
85   int dequote              /* True to dequote pCollName */
86 ){
87   if( pCollName->n>0 ){
88     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89     if( pNew ){
90       pNew->pLeft = pExpr;
91       pNew->flags |= EP_Collate|EP_Skip;
92       pExpr = pNew;
93     }
94   }
95   return pExpr;
96 }
97 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
98   Token s;
99   assert( zC!=0 );
100   sqlite3TokenInit(&s, (char*)zC);
101   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
102 }
103 
104 /*
105 ** Skip over any TK_COLLATE operators and any unlikely()
106 ** or likelihood() function at the root of an expression.
107 */
108 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
109   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
110     if( ExprHasProperty(pExpr, EP_Unlikely) ){
111       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
112       assert( pExpr->x.pList->nExpr>0 );
113       assert( pExpr->op==TK_FUNCTION );
114       pExpr = pExpr->x.pList->a[0].pExpr;
115     }else{
116       assert( pExpr->op==TK_COLLATE );
117       pExpr = pExpr->pLeft;
118     }
119   }
120   return pExpr;
121 }
122 
123 /*
124 ** Return the collation sequence for the expression pExpr. If
125 ** there is no defined collating sequence, return NULL.
126 **
127 ** The collating sequence might be determined by a COLLATE operator
128 ** or by the presence of a column with a defined collating sequence.
129 ** COLLATE operators take first precedence.  Left operands take
130 ** precedence over right operands.
131 */
132 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
133   sqlite3 *db = pParse->db;
134   CollSeq *pColl = 0;
135   Expr *p = pExpr;
136   while( p ){
137     int op = p->op;
138     if( p->flags & EP_Generic ) break;
139     if( op==TK_CAST || op==TK_UPLUS ){
140       p = p->pLeft;
141       continue;
142     }
143     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
144       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
145       break;
146     }
147     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
148           || op==TK_REGISTER || op==TK_TRIGGER)
149      && p->pTab!=0
150     ){
151       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
152       ** a TK_COLUMN but was previously evaluated and cached in a register */
153       int j = p->iColumn;
154       if( j>=0 ){
155         const char *zColl = p->pTab->aCol[j].zColl;
156         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
157       }
158       break;
159     }
160     if( p->flags & EP_Collate ){
161       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
162         p = p->pLeft;
163       }else{
164         Expr *pNext  = p->pRight;
165         /* The Expr.x union is never used at the same time as Expr.pRight */
166         assert( p->x.pList==0 || p->pRight==0 );
167         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
168         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
169         ** least one EP_Collate. Thus the following two ALWAYS. */
170         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
171           int i;
172           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
173             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
174               pNext = p->x.pList->a[i].pExpr;
175               break;
176             }
177           }
178         }
179         p = pNext;
180       }
181     }else{
182       break;
183     }
184   }
185   if( sqlite3CheckCollSeq(pParse, pColl) ){
186     pColl = 0;
187   }
188   return pColl;
189 }
190 
191 /*
192 ** pExpr is an operand of a comparison operator.  aff2 is the
193 ** type affinity of the other operand.  This routine returns the
194 ** type affinity that should be used for the comparison operator.
195 */
196 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
197   char aff1 = sqlite3ExprAffinity(pExpr);
198   if( aff1 && aff2 ){
199     /* Both sides of the comparison are columns. If one has numeric
200     ** affinity, use that. Otherwise use no affinity.
201     */
202     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
203       return SQLITE_AFF_NUMERIC;
204     }else{
205       return SQLITE_AFF_BLOB;
206     }
207   }else if( !aff1 && !aff2 ){
208     /* Neither side of the comparison is a column.  Compare the
209     ** results directly.
210     */
211     return SQLITE_AFF_BLOB;
212   }else{
213     /* One side is a column, the other is not. Use the columns affinity. */
214     assert( aff1==0 || aff2==0 );
215     return (aff1 + aff2);
216   }
217 }
218 
219 /*
220 ** pExpr is a comparison operator.  Return the type affinity that should
221 ** be applied to both operands prior to doing the comparison.
222 */
223 static char comparisonAffinity(Expr *pExpr){
224   char aff;
225   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
226           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
227           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
228   assert( pExpr->pLeft );
229   aff = sqlite3ExprAffinity(pExpr->pLeft);
230   if( pExpr->pRight ){
231     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
232   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
233     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
234   }else if( aff==0 ){
235     aff = SQLITE_AFF_BLOB;
236   }
237   return aff;
238 }
239 
240 /*
241 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
242 ** idx_affinity is the affinity of an indexed column. Return true
243 ** if the index with affinity idx_affinity may be used to implement
244 ** the comparison in pExpr.
245 */
246 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
247   char aff = comparisonAffinity(pExpr);
248   switch( aff ){
249     case SQLITE_AFF_BLOB:
250       return 1;
251     case SQLITE_AFF_TEXT:
252       return idx_affinity==SQLITE_AFF_TEXT;
253     default:
254       return sqlite3IsNumericAffinity(idx_affinity);
255   }
256 }
257 
258 /*
259 ** Return the P5 value that should be used for a binary comparison
260 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
261 */
262 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
263   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
264   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
265   return aff;
266 }
267 
268 /*
269 ** Return a pointer to the collation sequence that should be used by
270 ** a binary comparison operator comparing pLeft and pRight.
271 **
272 ** If the left hand expression has a collating sequence type, then it is
273 ** used. Otherwise the collation sequence for the right hand expression
274 ** is used, or the default (BINARY) if neither expression has a collating
275 ** type.
276 **
277 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
278 ** it is not considered.
279 */
280 CollSeq *sqlite3BinaryCompareCollSeq(
281   Parse *pParse,
282   Expr *pLeft,
283   Expr *pRight
284 ){
285   CollSeq *pColl;
286   assert( pLeft );
287   if( pLeft->flags & EP_Collate ){
288     pColl = sqlite3ExprCollSeq(pParse, pLeft);
289   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
290     pColl = sqlite3ExprCollSeq(pParse, pRight);
291   }else{
292     pColl = sqlite3ExprCollSeq(pParse, pLeft);
293     if( !pColl ){
294       pColl = sqlite3ExprCollSeq(pParse, pRight);
295     }
296   }
297   return pColl;
298 }
299 
300 /*
301 ** Generate code for a comparison operator.
302 */
303 static int codeCompare(
304   Parse *pParse,    /* The parsing (and code generating) context */
305   Expr *pLeft,      /* The left operand */
306   Expr *pRight,     /* The right operand */
307   int opcode,       /* The comparison opcode */
308   int in1, int in2, /* Register holding operands */
309   int dest,         /* Jump here if true.  */
310   int jumpIfNull    /* If true, jump if either operand is NULL */
311 ){
312   int p5;
313   int addr;
314   CollSeq *p4;
315 
316   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
317   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
318   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
319                            (void*)p4, P4_COLLSEQ);
320   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
321   return addr;
322 }
323 
324 /*
325 ** Return true if expression pExpr is a vector, or false otherwise.
326 **
327 ** A vector is defined as any expression that results in two or more
328 ** columns of result.  Every TK_VECTOR node is an vector because the
329 ** parser will not generate a TK_VECTOR with fewer than two entries.
330 ** But a TK_SELECT might be either a vector or a scalar. It is only
331 ** considered a vector if it has two or more result columns.
332 */
333 int sqlite3ExprIsVector(Expr *pExpr){
334   return sqlite3ExprVectorSize(pExpr)>1;
335 }
336 
337 /*
338 ** If the expression passed as the only argument is of type TK_VECTOR
339 ** return the number of expressions in the vector. Or, if the expression
340 ** is a sub-select, return the number of columns in the sub-select. For
341 ** any other type of expression, return 1.
342 */
343 int sqlite3ExprVectorSize(Expr *pExpr){
344   u8 op = pExpr->op;
345   if( op==TK_REGISTER ) op = pExpr->op2;
346   if( op==TK_VECTOR ){
347     return pExpr->x.pList->nExpr;
348   }else if( op==TK_SELECT ){
349     return pExpr->x.pSelect->pEList->nExpr;
350   }else{
351     return 1;
352   }
353 }
354 
355 /*
356 ** Return a pointer to a subexpression of pVector that is the i-th
357 ** column of the vector (numbered starting with 0).  The caller must
358 ** ensure that i is within range.
359 **
360 ** If pVector is really a scalar (and "scalar" here includes subqueries
361 ** that return a single column!) then return pVector unmodified.
362 **
363 ** pVector retains ownership of the returned subexpression.
364 **
365 ** If the vector is a (SELECT ...) then the expression returned is
366 ** just the expression for the i-th term of the result set, and may
367 ** not be ready for evaluation because the table cursor has not yet
368 ** been positioned.
369 */
370 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
371   assert( i<sqlite3ExprVectorSize(pVector) );
372   if( sqlite3ExprIsVector(pVector) ){
373     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
374     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
375       return pVector->x.pSelect->pEList->a[i].pExpr;
376     }else{
377       return pVector->x.pList->a[i].pExpr;
378     }
379   }
380   return pVector;
381 }
382 
383 /*
384 ** Compute and return a new Expr object which when passed to
385 ** sqlite3ExprCode() will generate all necessary code to compute
386 ** the iField-th column of the vector expression pVector.
387 **
388 ** It is ok for pVector to be a scalar (as long as iField==0).
389 ** In that case, this routine works like sqlite3ExprDup().
390 **
391 ** The caller owns the returned Expr object and is responsible for
392 ** ensuring that the returned value eventually gets freed.
393 **
394 ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
395 ** then the returned object will reference pVector and so pVector must remain
396 ** valid for the life of the returned object.  If pVector is a TK_VECTOR
397 ** or a scalar expression, then it can be deleted as soon as this routine
398 ** returns.
399 **
400 ** A trick to cause a TK_SELECT pVector to be deleted together with
401 ** the returned Expr object is to attach the pVector to the pRight field
402 ** of the returned TK_SELECT_COLUMN Expr object.
403 */
404 Expr *sqlite3ExprForVectorField(
405   Parse *pParse,       /* Parsing context */
406   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
407   int iField           /* Which column of the vector to return */
408 ){
409   Expr *pRet;
410   if( pVector->op==TK_SELECT ){
411     assert( pVector->flags & EP_xIsSelect );
412     /* The TK_SELECT_COLUMN Expr node:
413     **
414     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
415     ** pRight:          not used.  But recursively deleted.
416     ** iColumn:         Index of a column in pVector
417     ** iTable:          0 or the number of columns on the LHS of an assignment
418     ** pLeft->iTable:   First in an array of register holding result, or 0
419     **                  if the result is not yet computed.
420     **
421     ** sqlite3ExprDelete() specifically skips the recursive delete of
422     ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
423     ** can be attached to pRight to cause this node to take ownership of
424     ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
425     ** with the same pLeft pointer to the pVector, but only one of them
426     ** will own the pVector.
427     */
428     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
429     if( pRet ){
430       pRet->iColumn = iField;
431       pRet->pLeft = pVector;
432     }
433     assert( pRet==0 || pRet->iTable==0 );
434   }else{
435     if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
436     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
437   }
438   return pRet;
439 }
440 
441 /*
442 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
443 ** it. Return the register in which the result is stored (or, if the
444 ** sub-select returns more than one column, the first in an array
445 ** of registers in which the result is stored).
446 **
447 ** If pExpr is not a TK_SELECT expression, return 0.
448 */
449 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
450   int reg = 0;
451 #ifndef SQLITE_OMIT_SUBQUERY
452   if( pExpr->op==TK_SELECT ){
453     reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
454   }
455 #endif
456   return reg;
457 }
458 
459 /*
460 ** Argument pVector points to a vector expression - either a TK_VECTOR
461 ** or TK_SELECT that returns more than one column. This function returns
462 ** the register number of a register that contains the value of
463 ** element iField of the vector.
464 **
465 ** If pVector is a TK_SELECT expression, then code for it must have
466 ** already been generated using the exprCodeSubselect() routine. In this
467 ** case parameter regSelect should be the first in an array of registers
468 ** containing the results of the sub-select.
469 **
470 ** If pVector is of type TK_VECTOR, then code for the requested field
471 ** is generated. In this case (*pRegFree) may be set to the number of
472 ** a temporary register to be freed by the caller before returning.
473 **
474 ** Before returning, output parameter (*ppExpr) is set to point to the
475 ** Expr object corresponding to element iElem of the vector.
476 */
477 static int exprVectorRegister(
478   Parse *pParse,                  /* Parse context */
479   Expr *pVector,                  /* Vector to extract element from */
480   int iField,                     /* Field to extract from pVector */
481   int regSelect,                  /* First in array of registers */
482   Expr **ppExpr,                  /* OUT: Expression element */
483   int *pRegFree                   /* OUT: Temp register to free */
484 ){
485   u8 op = pVector->op;
486   assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
487   if( op==TK_REGISTER ){
488     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
489     return pVector->iTable+iField;
490   }
491   if( op==TK_SELECT ){
492     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
493      return regSelect+iField;
494   }
495   *ppExpr = pVector->x.pList->a[iField].pExpr;
496   return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
497 }
498 
499 /*
500 ** Expression pExpr is a comparison between two vector values. Compute
501 ** the result of the comparison (1, 0, or NULL) and write that
502 ** result into register dest.
503 **
504 ** The caller must satisfy the following preconditions:
505 **
506 **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
507 **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
508 **    otherwise:                op==pExpr->op and p5==0
509 */
510 static void codeVectorCompare(
511   Parse *pParse,        /* Code generator context */
512   Expr *pExpr,          /* The comparison operation */
513   int dest,             /* Write results into this register */
514   u8 op,                /* Comparison operator */
515   u8 p5                 /* SQLITE_NULLEQ or zero */
516 ){
517   Vdbe *v = pParse->pVdbe;
518   Expr *pLeft = pExpr->pLeft;
519   Expr *pRight = pExpr->pRight;
520   int nLeft = sqlite3ExprVectorSize(pLeft);
521   int i;
522   int regLeft = 0;
523   int regRight = 0;
524   u8 opx = op;
525   int addrDone = sqlite3VdbeMakeLabel(v);
526 
527   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
528     sqlite3ErrorMsg(pParse, "row value misused");
529     return;
530   }
531   assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
532        || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
533        || pExpr->op==TK_LT || pExpr->op==TK_GT
534        || pExpr->op==TK_LE || pExpr->op==TK_GE
535   );
536   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
537             || (pExpr->op==TK_ISNOT && op==TK_NE) );
538   assert( p5==0 || pExpr->op!=op );
539   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
540 
541   p5 |= SQLITE_STOREP2;
542   if( opx==TK_LE ) opx = TK_LT;
543   if( opx==TK_GE ) opx = TK_GT;
544 
545   regLeft = exprCodeSubselect(pParse, pLeft);
546   regRight = exprCodeSubselect(pParse, pRight);
547 
548   for(i=0; 1 /*Loop exits by "break"*/; i++){
549     int regFree1 = 0, regFree2 = 0;
550     Expr *pL, *pR;
551     int r1, r2;
552     assert( i>=0 && i<nLeft );
553     if( i>0 ) sqlite3ExprCachePush(pParse);
554     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
555     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
556     codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
557     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
558     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
559     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
560     testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
561     testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
562     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
563     sqlite3ReleaseTempReg(pParse, regFree1);
564     sqlite3ReleaseTempReg(pParse, regFree2);
565     if( i>0 ) sqlite3ExprCachePop(pParse);
566     if( i==nLeft-1 ){
567       break;
568     }
569     if( opx==TK_EQ ){
570       sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
571       p5 |= SQLITE_KEEPNULL;
572     }else if( opx==TK_NE ){
573       sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
574       p5 |= SQLITE_KEEPNULL;
575     }else{
576       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
577       sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
578       VdbeCoverageIf(v, op==TK_LT);
579       VdbeCoverageIf(v, op==TK_GT);
580       VdbeCoverageIf(v, op==TK_LE);
581       VdbeCoverageIf(v, op==TK_GE);
582       if( i==nLeft-2 ) opx = op;
583     }
584   }
585   sqlite3VdbeResolveLabel(v, addrDone);
586 }
587 
588 #if SQLITE_MAX_EXPR_DEPTH>0
589 /*
590 ** Check that argument nHeight is less than or equal to the maximum
591 ** expression depth allowed. If it is not, leave an error message in
592 ** pParse.
593 */
594 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
595   int rc = SQLITE_OK;
596   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
597   if( nHeight>mxHeight ){
598     sqlite3ErrorMsg(pParse,
599        "Expression tree is too large (maximum depth %d)", mxHeight
600     );
601     rc = SQLITE_ERROR;
602   }
603   return rc;
604 }
605 
606 /* The following three functions, heightOfExpr(), heightOfExprList()
607 ** and heightOfSelect(), are used to determine the maximum height
608 ** of any expression tree referenced by the structure passed as the
609 ** first argument.
610 **
611 ** If this maximum height is greater than the current value pointed
612 ** to by pnHeight, the second parameter, then set *pnHeight to that
613 ** value.
614 */
615 static void heightOfExpr(Expr *p, int *pnHeight){
616   if( p ){
617     if( p->nHeight>*pnHeight ){
618       *pnHeight = p->nHeight;
619     }
620   }
621 }
622 static void heightOfExprList(ExprList *p, int *pnHeight){
623   if( p ){
624     int i;
625     for(i=0; i<p->nExpr; i++){
626       heightOfExpr(p->a[i].pExpr, pnHeight);
627     }
628   }
629 }
630 static void heightOfSelect(Select *p, int *pnHeight){
631   if( p ){
632     heightOfExpr(p->pWhere, pnHeight);
633     heightOfExpr(p->pHaving, pnHeight);
634     heightOfExpr(p->pLimit, pnHeight);
635     heightOfExpr(p->pOffset, pnHeight);
636     heightOfExprList(p->pEList, pnHeight);
637     heightOfExprList(p->pGroupBy, pnHeight);
638     heightOfExprList(p->pOrderBy, pnHeight);
639     heightOfSelect(p->pPrior, pnHeight);
640   }
641 }
642 
643 /*
644 ** Set the Expr.nHeight variable in the structure passed as an
645 ** argument. An expression with no children, Expr.pList or
646 ** Expr.pSelect member has a height of 1. Any other expression
647 ** has a height equal to the maximum height of any other
648 ** referenced Expr plus one.
649 **
650 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
651 ** if appropriate.
652 */
653 static void exprSetHeight(Expr *p){
654   int nHeight = 0;
655   heightOfExpr(p->pLeft, &nHeight);
656   heightOfExpr(p->pRight, &nHeight);
657   if( ExprHasProperty(p, EP_xIsSelect) ){
658     heightOfSelect(p->x.pSelect, &nHeight);
659   }else if( p->x.pList ){
660     heightOfExprList(p->x.pList, &nHeight);
661     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
662   }
663   p->nHeight = nHeight + 1;
664 }
665 
666 /*
667 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
668 ** the height is greater than the maximum allowed expression depth,
669 ** leave an error in pParse.
670 **
671 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
672 ** Expr.flags.
673 */
674 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
675   if( pParse->nErr ) return;
676   exprSetHeight(p);
677   sqlite3ExprCheckHeight(pParse, p->nHeight);
678 }
679 
680 /*
681 ** Return the maximum height of any expression tree referenced
682 ** by the select statement passed as an argument.
683 */
684 int sqlite3SelectExprHeight(Select *p){
685   int nHeight = 0;
686   heightOfSelect(p, &nHeight);
687   return nHeight;
688 }
689 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
690 /*
691 ** Propagate all EP_Propagate flags from the Expr.x.pList into
692 ** Expr.flags.
693 */
694 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
695   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
696     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
697   }
698 }
699 #define exprSetHeight(y)
700 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
701 
702 /*
703 ** This routine is the core allocator for Expr nodes.
704 **
705 ** Construct a new expression node and return a pointer to it.  Memory
706 ** for this node and for the pToken argument is a single allocation
707 ** obtained from sqlite3DbMalloc().  The calling function
708 ** is responsible for making sure the node eventually gets freed.
709 **
710 ** If dequote is true, then the token (if it exists) is dequoted.
711 ** If dequote is false, no dequoting is performed.  The deQuote
712 ** parameter is ignored if pToken is NULL or if the token does not
713 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
714 ** then the EP_DblQuoted flag is set on the expression node.
715 **
716 ** Special case:  If op==TK_INTEGER and pToken points to a string that
717 ** can be translated into a 32-bit integer, then the token is not
718 ** stored in u.zToken.  Instead, the integer values is written
719 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
720 ** is allocated to hold the integer text and the dequote flag is ignored.
721 */
722 Expr *sqlite3ExprAlloc(
723   sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
724   int op,                 /* Expression opcode */
725   const Token *pToken,    /* Token argument.  Might be NULL */
726   int dequote             /* True to dequote */
727 ){
728   Expr *pNew;
729   int nExtra = 0;
730   int iValue = 0;
731 
732   assert( db!=0 );
733   if( pToken ){
734     if( op!=TK_INTEGER || pToken->z==0
735           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
736       nExtra = pToken->n+1;
737       assert( iValue>=0 );
738     }
739   }
740   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
741   if( pNew ){
742     memset(pNew, 0, sizeof(Expr));
743     pNew->op = (u8)op;
744     pNew->iAgg = -1;
745     if( pToken ){
746       if( nExtra==0 ){
747         pNew->flags |= EP_IntValue;
748         pNew->u.iValue = iValue;
749       }else{
750         pNew->u.zToken = (char*)&pNew[1];
751         assert( pToken->z!=0 || pToken->n==0 );
752         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
753         pNew->u.zToken[pToken->n] = 0;
754         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
755           if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
756           sqlite3Dequote(pNew->u.zToken);
757         }
758       }
759     }
760 #if SQLITE_MAX_EXPR_DEPTH>0
761     pNew->nHeight = 1;
762 #endif
763   }
764   return pNew;
765 }
766 
767 /*
768 ** Allocate a new expression node from a zero-terminated token that has
769 ** already been dequoted.
770 */
771 Expr *sqlite3Expr(
772   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
773   int op,                 /* Expression opcode */
774   const char *zToken      /* Token argument.  Might be NULL */
775 ){
776   Token x;
777   x.z = zToken;
778   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
779   return sqlite3ExprAlloc(db, op, &x, 0);
780 }
781 
782 /*
783 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
784 **
785 ** If pRoot==NULL that means that a memory allocation error has occurred.
786 ** In that case, delete the subtrees pLeft and pRight.
787 */
788 void sqlite3ExprAttachSubtrees(
789   sqlite3 *db,
790   Expr *pRoot,
791   Expr *pLeft,
792   Expr *pRight
793 ){
794   if( pRoot==0 ){
795     assert( db->mallocFailed );
796     sqlite3ExprDelete(db, pLeft);
797     sqlite3ExprDelete(db, pRight);
798   }else{
799     if( pRight ){
800       pRoot->pRight = pRight;
801       pRoot->flags |= EP_Propagate & pRight->flags;
802     }
803     if( pLeft ){
804       pRoot->pLeft = pLeft;
805       pRoot->flags |= EP_Propagate & pLeft->flags;
806     }
807     exprSetHeight(pRoot);
808   }
809 }
810 
811 /*
812 ** Allocate an Expr node which joins as many as two subtrees.
813 **
814 ** One or both of the subtrees can be NULL.  Return a pointer to the new
815 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
816 ** free the subtrees and return NULL.
817 */
818 Expr *sqlite3PExpr(
819   Parse *pParse,          /* Parsing context */
820   int op,                 /* Expression opcode */
821   Expr *pLeft,            /* Left operand */
822   Expr *pRight            /* Right operand */
823 ){
824   Expr *p;
825   if( op==TK_AND && pParse->nErr==0 ){
826     /* Take advantage of short-circuit false optimization for AND */
827     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
828   }else{
829     p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
830     if( p ){
831       memset(p, 0, sizeof(Expr));
832       p->op = op & TKFLG_MASK;
833       p->iAgg = -1;
834     }
835     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
836   }
837   if( p ) {
838     sqlite3ExprCheckHeight(pParse, p->nHeight);
839   }
840   return p;
841 }
842 
843 /*
844 ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
845 ** do a memory allocation failure) then delete the pSelect object.
846 */
847 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
848   if( pExpr ){
849     pExpr->x.pSelect = pSelect;
850     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
851     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
852   }else{
853     assert( pParse->db->mallocFailed );
854     sqlite3SelectDelete(pParse->db, pSelect);
855   }
856 }
857 
858 
859 /*
860 ** If the expression is always either TRUE or FALSE (respectively),
861 ** then return 1.  If one cannot determine the truth value of the
862 ** expression at compile-time return 0.
863 **
864 ** This is an optimization.  If is OK to return 0 here even if
865 ** the expression really is always false or false (a false negative).
866 ** But it is a bug to return 1 if the expression might have different
867 ** boolean values in different circumstances (a false positive.)
868 **
869 ** Note that if the expression is part of conditional for a
870 ** LEFT JOIN, then we cannot determine at compile-time whether or not
871 ** is it true or false, so always return 0.
872 */
873 static int exprAlwaysTrue(Expr *p){
874   int v = 0;
875   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
876   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
877   return v!=0;
878 }
879 static int exprAlwaysFalse(Expr *p){
880   int v = 0;
881   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
882   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
883   return v==0;
884 }
885 
886 /*
887 ** Join two expressions using an AND operator.  If either expression is
888 ** NULL, then just return the other expression.
889 **
890 ** If one side or the other of the AND is known to be false, then instead
891 ** of returning an AND expression, just return a constant expression with
892 ** a value of false.
893 */
894 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
895   if( pLeft==0 ){
896     return pRight;
897   }else if( pRight==0 ){
898     return pLeft;
899   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
900     sqlite3ExprDelete(db, pLeft);
901     sqlite3ExprDelete(db, pRight);
902     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
903   }else{
904     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
905     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
906     return pNew;
907   }
908 }
909 
910 /*
911 ** Construct a new expression node for a function with multiple
912 ** arguments.
913 */
914 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
915   Expr *pNew;
916   sqlite3 *db = pParse->db;
917   assert( pToken );
918   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
919   if( pNew==0 ){
920     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
921     return 0;
922   }
923   pNew->x.pList = pList;
924   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
925   sqlite3ExprSetHeightAndFlags(pParse, pNew);
926   return pNew;
927 }
928 
929 /*
930 ** Assign a variable number to an expression that encodes a wildcard
931 ** in the original SQL statement.
932 **
933 ** Wildcards consisting of a single "?" are assigned the next sequential
934 ** variable number.
935 **
936 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
937 ** sure "nnn" is not too big to avoid a denial of service attack when
938 ** the SQL statement comes from an external source.
939 **
940 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
941 ** as the previous instance of the same wildcard.  Or if this is the first
942 ** instance of the wildcard, the next sequential variable number is
943 ** assigned.
944 */
945 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
946   sqlite3 *db = pParse->db;
947   const char *z;
948   ynVar x;
949 
950   if( pExpr==0 ) return;
951   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
952   z = pExpr->u.zToken;
953   assert( z!=0 );
954   assert( z[0]!=0 );
955   assert( n==(u32)sqlite3Strlen30(z) );
956   if( z[1]==0 ){
957     /* Wildcard of the form "?".  Assign the next variable number */
958     assert( z[0]=='?' );
959     x = (ynVar)(++pParse->nVar);
960   }else{
961     int doAdd = 0;
962     if( z[0]=='?' ){
963       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
964       ** use it as the variable number */
965       i64 i;
966       int bOk;
967       if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
968         i = z[1]-'0';  /* The common case of ?N for a single digit N */
969         bOk = 1;
970       }else{
971         bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
972       }
973       testcase( i==0 );
974       testcase( i==1 );
975       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
976       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
977       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
978         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
979             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
980         return;
981       }
982       x = (ynVar)i;
983       if( x>pParse->nVar ){
984         pParse->nVar = (int)x;
985         doAdd = 1;
986       }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
987         doAdd = 1;
988       }
989     }else{
990       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
991       ** number as the prior appearance of the same name, or if the name
992       ** has never appeared before, reuse the same variable number
993       */
994       x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
995       if( x==0 ){
996         x = (ynVar)(++pParse->nVar);
997         doAdd = 1;
998       }
999     }
1000     if( doAdd ){
1001       pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1002     }
1003   }
1004   pExpr->iColumn = x;
1005   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1006     sqlite3ErrorMsg(pParse, "too many SQL variables");
1007   }
1008 }
1009 
1010 /*
1011 ** Recursively delete an expression tree.
1012 */
1013 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1014   assert( p!=0 );
1015   /* Sanity check: Assert that the IntValue is non-negative if it exists */
1016   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1017 #ifdef SQLITE_DEBUG
1018   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1019     assert( p->pLeft==0 );
1020     assert( p->pRight==0 );
1021     assert( p->x.pSelect==0 );
1022   }
1023 #endif
1024   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1025     /* The Expr.x union is never used at the same time as Expr.pRight */
1026     assert( p->x.pList==0 || p->pRight==0 );
1027     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1028     sqlite3ExprDelete(db, p->pRight);
1029     if( ExprHasProperty(p, EP_xIsSelect) ){
1030       sqlite3SelectDelete(db, p->x.pSelect);
1031     }else{
1032       sqlite3ExprListDelete(db, p->x.pList);
1033     }
1034   }
1035   if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
1036   if( !ExprHasProperty(p, EP_Static) ){
1037     sqlite3DbFreeNN(db, p);
1038   }
1039 }
1040 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1041   if( p ) sqlite3ExprDeleteNN(db, p);
1042 }
1043 
1044 /*
1045 ** Return the number of bytes allocated for the expression structure
1046 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1047 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1048 */
1049 static int exprStructSize(Expr *p){
1050   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1051   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1052   return EXPR_FULLSIZE;
1053 }
1054 
1055 /*
1056 ** The dupedExpr*Size() routines each return the number of bytes required
1057 ** to store a copy of an expression or expression tree.  They differ in
1058 ** how much of the tree is measured.
1059 **
1060 **     dupedExprStructSize()     Size of only the Expr structure
1061 **     dupedExprNodeSize()       Size of Expr + space for token
1062 **     dupedExprSize()           Expr + token + subtree components
1063 **
1064 ***************************************************************************
1065 **
1066 ** The dupedExprStructSize() function returns two values OR-ed together:
1067 ** (1) the space required for a copy of the Expr structure only and
1068 ** (2) the EP_xxx flags that indicate what the structure size should be.
1069 ** The return values is always one of:
1070 **
1071 **      EXPR_FULLSIZE
1072 **      EXPR_REDUCEDSIZE   | EP_Reduced
1073 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
1074 **
1075 ** The size of the structure can be found by masking the return value
1076 ** of this routine with 0xfff.  The flags can be found by masking the
1077 ** return value with EP_Reduced|EP_TokenOnly.
1078 **
1079 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1080 ** (unreduced) Expr objects as they or originally constructed by the parser.
1081 ** During expression analysis, extra information is computed and moved into
1082 ** later parts of teh Expr object and that extra information might get chopped
1083 ** off if the expression is reduced.  Note also that it does not work to
1084 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
1085 ** to reduce a pristine expression tree from the parser.  The implementation
1086 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1087 ** to enforce this constraint.
1088 */
1089 static int dupedExprStructSize(Expr *p, int flags){
1090   int nSize;
1091   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1092   assert( EXPR_FULLSIZE<=0xfff );
1093   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1094   if( 0==flags || p->op==TK_SELECT_COLUMN ){
1095     nSize = EXPR_FULLSIZE;
1096   }else{
1097     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1098     assert( !ExprHasProperty(p, EP_FromJoin) );
1099     assert( !ExprHasProperty(p, EP_MemToken) );
1100     assert( !ExprHasProperty(p, EP_NoReduce) );
1101     if( p->pLeft || p->x.pList ){
1102       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1103     }else{
1104       assert( p->pRight==0 );
1105       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1106     }
1107   }
1108   return nSize;
1109 }
1110 
1111 /*
1112 ** This function returns the space in bytes required to store the copy
1113 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1114 ** string is defined.)
1115 */
1116 static int dupedExprNodeSize(Expr *p, int flags){
1117   int nByte = dupedExprStructSize(p, flags) & 0xfff;
1118   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1119     nByte += sqlite3Strlen30(p->u.zToken)+1;
1120   }
1121   return ROUND8(nByte);
1122 }
1123 
1124 /*
1125 ** Return the number of bytes required to create a duplicate of the
1126 ** expression passed as the first argument. The second argument is a
1127 ** mask containing EXPRDUP_XXX flags.
1128 **
1129 ** The value returned includes space to create a copy of the Expr struct
1130 ** itself and the buffer referred to by Expr.u.zToken, if any.
1131 **
1132 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1133 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1134 ** and Expr.pRight variables (but not for any structures pointed to or
1135 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1136 */
1137 static int dupedExprSize(Expr *p, int flags){
1138   int nByte = 0;
1139   if( p ){
1140     nByte = dupedExprNodeSize(p, flags);
1141     if( flags&EXPRDUP_REDUCE ){
1142       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1143     }
1144   }
1145   return nByte;
1146 }
1147 
1148 /*
1149 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1150 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1151 ** to store the copy of expression p, the copies of p->u.zToken
1152 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1153 ** if any. Before returning, *pzBuffer is set to the first byte past the
1154 ** portion of the buffer copied into by this function.
1155 */
1156 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1157   Expr *pNew;           /* Value to return */
1158   u8 *zAlloc;           /* Memory space from which to build Expr object */
1159   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
1160 
1161   assert( db!=0 );
1162   assert( p );
1163   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1164   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1165 
1166   /* Figure out where to write the new Expr structure. */
1167   if( pzBuffer ){
1168     zAlloc = *pzBuffer;
1169     staticFlag = EP_Static;
1170   }else{
1171     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1172     staticFlag = 0;
1173   }
1174   pNew = (Expr *)zAlloc;
1175 
1176   if( pNew ){
1177     /* Set nNewSize to the size allocated for the structure pointed to
1178     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1179     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1180     ** by the copy of the p->u.zToken string (if any).
1181     */
1182     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1183     const int nNewSize = nStructSize & 0xfff;
1184     int nToken;
1185     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1186       nToken = sqlite3Strlen30(p->u.zToken) + 1;
1187     }else{
1188       nToken = 0;
1189     }
1190     if( dupFlags ){
1191       assert( ExprHasProperty(p, EP_Reduced)==0 );
1192       memcpy(zAlloc, p, nNewSize);
1193     }else{
1194       u32 nSize = (u32)exprStructSize(p);
1195       memcpy(zAlloc, p, nSize);
1196       if( nSize<EXPR_FULLSIZE ){
1197         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1198       }
1199     }
1200 
1201     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1202     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1203     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1204     pNew->flags |= staticFlag;
1205 
1206     /* Copy the p->u.zToken string, if any. */
1207     if( nToken ){
1208       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1209       memcpy(zToken, p->u.zToken, nToken);
1210     }
1211 
1212     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1213       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1214       if( ExprHasProperty(p, EP_xIsSelect) ){
1215         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1216       }else{
1217         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1218       }
1219     }
1220 
1221     /* Fill in pNew->pLeft and pNew->pRight. */
1222     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1223       zAlloc += dupedExprNodeSize(p, dupFlags);
1224       if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1225         pNew->pLeft = p->pLeft ?
1226                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1227         pNew->pRight = p->pRight ?
1228                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1229       }
1230       if( pzBuffer ){
1231         *pzBuffer = zAlloc;
1232       }
1233     }else{
1234       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1235         if( pNew->op==TK_SELECT_COLUMN ){
1236           pNew->pLeft = p->pLeft;
1237           assert( p->iColumn==0 || p->pRight==0 );
1238           assert( p->pRight==0  || p->pRight==p->pLeft );
1239         }else{
1240           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1241         }
1242         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1243       }
1244     }
1245   }
1246   return pNew;
1247 }
1248 
1249 /*
1250 ** Create and return a deep copy of the object passed as the second
1251 ** argument. If an OOM condition is encountered, NULL is returned
1252 ** and the db->mallocFailed flag set.
1253 */
1254 #ifndef SQLITE_OMIT_CTE
1255 static With *withDup(sqlite3 *db, With *p){
1256   With *pRet = 0;
1257   if( p ){
1258     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1259     pRet = sqlite3DbMallocZero(db, nByte);
1260     if( pRet ){
1261       int i;
1262       pRet->nCte = p->nCte;
1263       for(i=0; i<p->nCte; i++){
1264         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1265         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1266         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1267       }
1268     }
1269   }
1270   return pRet;
1271 }
1272 #else
1273 # define withDup(x,y) 0
1274 #endif
1275 
1276 /*
1277 ** The following group of routines make deep copies of expressions,
1278 ** expression lists, ID lists, and select statements.  The copies can
1279 ** be deleted (by being passed to their respective ...Delete() routines)
1280 ** without effecting the originals.
1281 **
1282 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1283 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1284 ** by subsequent calls to sqlite*ListAppend() routines.
1285 **
1286 ** Any tables that the SrcList might point to are not duplicated.
1287 **
1288 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1289 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1290 ** truncated version of the usual Expr structure that will be stored as
1291 ** part of the in-memory representation of the database schema.
1292 */
1293 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
1294   assert( flags==0 || flags==EXPRDUP_REDUCE );
1295   return p ? exprDup(db, p, flags, 0) : 0;
1296 }
1297 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1298   ExprList *pNew;
1299   struct ExprList_item *pItem, *pOldItem;
1300   int i;
1301   Expr *pPriorSelectCol = 0;
1302   assert( db!=0 );
1303   if( p==0 ) return 0;
1304   pNew = sqlite3DbMallocRawNN(db,
1305              sizeof(*pNew)+sizeof(pNew->a[0])*(p->nExpr-1) );
1306   if( pNew==0 ) return 0;
1307   pNew->nAlloc = pNew->nExpr = p->nExpr;
1308   pItem = pNew->a;
1309   pOldItem = p->a;
1310   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1311     Expr *pOldExpr = pOldItem->pExpr;
1312     Expr *pNewExpr;
1313     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1314     if( pOldExpr
1315      && pOldExpr->op==TK_SELECT_COLUMN
1316      && (pNewExpr = pItem->pExpr)!=0
1317     ){
1318       assert( pNewExpr->iColumn==0 || i>0 );
1319       if( pNewExpr->iColumn==0 ){
1320         assert( pOldExpr->pLeft==pOldExpr->pRight );
1321         pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
1322       }else{
1323         assert( i>0 );
1324         assert( pItem[-1].pExpr!=0 );
1325         assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1326         assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1327         pNewExpr->pLeft = pPriorSelectCol;
1328       }
1329     }
1330     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1331     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1332     pItem->sortOrder = pOldItem->sortOrder;
1333     pItem->done = 0;
1334     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
1335     pItem->u = pOldItem->u;
1336   }
1337   return pNew;
1338 }
1339 
1340 /*
1341 ** If cursors, triggers, views and subqueries are all omitted from
1342 ** the build, then none of the following routines, except for
1343 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1344 ** called with a NULL argument.
1345 */
1346 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1347  || !defined(SQLITE_OMIT_SUBQUERY)
1348 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1349   SrcList *pNew;
1350   int i;
1351   int nByte;
1352   assert( db!=0 );
1353   if( p==0 ) return 0;
1354   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1355   pNew = sqlite3DbMallocRawNN(db, nByte );
1356   if( pNew==0 ) return 0;
1357   pNew->nSrc = pNew->nAlloc = p->nSrc;
1358   for(i=0; i<p->nSrc; i++){
1359     struct SrcList_item *pNewItem = &pNew->a[i];
1360     struct SrcList_item *pOldItem = &p->a[i];
1361     Table *pTab;
1362     pNewItem->pSchema = pOldItem->pSchema;
1363     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1364     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1365     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1366     pNewItem->fg = pOldItem->fg;
1367     pNewItem->iCursor = pOldItem->iCursor;
1368     pNewItem->addrFillSub = pOldItem->addrFillSub;
1369     pNewItem->regReturn = pOldItem->regReturn;
1370     if( pNewItem->fg.isIndexedBy ){
1371       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1372     }
1373     pNewItem->pIBIndex = pOldItem->pIBIndex;
1374     if( pNewItem->fg.isTabFunc ){
1375       pNewItem->u1.pFuncArg =
1376           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1377     }
1378     pTab = pNewItem->pTab = pOldItem->pTab;
1379     if( pTab ){
1380       pTab->nTabRef++;
1381     }
1382     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1383     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
1384     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1385     pNewItem->colUsed = pOldItem->colUsed;
1386   }
1387   return pNew;
1388 }
1389 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1390   IdList *pNew;
1391   int i;
1392   assert( db!=0 );
1393   if( p==0 ) return 0;
1394   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1395   if( pNew==0 ) return 0;
1396   pNew->nId = p->nId;
1397   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1398   if( pNew->a==0 ){
1399     sqlite3DbFreeNN(db, pNew);
1400     return 0;
1401   }
1402   /* Note that because the size of the allocation for p->a[] is not
1403   ** necessarily a power of two, sqlite3IdListAppend() may not be called
1404   ** on the duplicate created by this function. */
1405   for(i=0; i<p->nId; i++){
1406     struct IdList_item *pNewItem = &pNew->a[i];
1407     struct IdList_item *pOldItem = &p->a[i];
1408     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1409     pNewItem->idx = pOldItem->idx;
1410   }
1411   return pNew;
1412 }
1413 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1414   Select *pRet = 0;
1415   Select *pNext = 0;
1416   Select **pp = &pRet;
1417   Select *p;
1418 
1419   assert( db!=0 );
1420   for(p=pDup; p; p=p->pPrior){
1421     Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1422     if( pNew==0 ) break;
1423     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1424     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1425     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1426     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1427     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1428     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1429     pNew->op = p->op;
1430     pNew->pNext = pNext;
1431     pNew->pPrior = 0;
1432     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1433     pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
1434     pNew->iLimit = 0;
1435     pNew->iOffset = 0;
1436     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1437     pNew->addrOpenEphm[0] = -1;
1438     pNew->addrOpenEphm[1] = -1;
1439     pNew->nSelectRow = p->nSelectRow;
1440     pNew->pWith = withDup(db, p->pWith);
1441     sqlite3SelectSetName(pNew, p->zSelName);
1442     *pp = pNew;
1443     pp = &pNew->pPrior;
1444     pNext = pNew;
1445   }
1446 
1447   return pRet;
1448 }
1449 #else
1450 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1451   assert( p==0 );
1452   return 0;
1453 }
1454 #endif
1455 
1456 
1457 /*
1458 ** Add a new element to the end of an expression list.  If pList is
1459 ** initially NULL, then create a new expression list.
1460 **
1461 ** If a memory allocation error occurs, the entire list is freed and
1462 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1463 ** that the new entry was successfully appended.
1464 */
1465 ExprList *sqlite3ExprListAppend(
1466   Parse *pParse,          /* Parsing context */
1467   ExprList *pList,        /* List to which to append. Might be NULL */
1468   Expr *pExpr             /* Expression to be appended. Might be NULL */
1469 ){
1470   struct ExprList_item *pItem;
1471   sqlite3 *db = pParse->db;
1472   assert( db!=0 );
1473   if( pList==0 ){
1474     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1475     if( pList==0 ){
1476       goto no_mem;
1477     }
1478     pList->nExpr = 0;
1479     pList->nAlloc = 1;
1480   }else if( pList->nExpr==pList->nAlloc ){
1481     ExprList *pNew;
1482     pNew = sqlite3DbRealloc(db, pList,
1483              sizeof(*pList)+(2*pList->nAlloc - 1)*sizeof(pList->a[0]));
1484     if( pNew==0 ){
1485       goto no_mem;
1486     }
1487     pList = pNew;
1488     pList->nAlloc *= 2;
1489   }
1490   pItem = &pList->a[pList->nExpr++];
1491   assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
1492   assert( offsetof(struct ExprList_item,pExpr)==0 );
1493   memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
1494   pItem->pExpr = pExpr;
1495   return pList;
1496 
1497 no_mem:
1498   /* Avoid leaking memory if malloc has failed. */
1499   sqlite3ExprDelete(db, pExpr);
1500   sqlite3ExprListDelete(db, pList);
1501   return 0;
1502 }
1503 
1504 /*
1505 ** pColumns and pExpr form a vector assignment which is part of the SET
1506 ** clause of an UPDATE statement.  Like this:
1507 **
1508 **        (a,b,c) = (expr1,expr2,expr3)
1509 ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
1510 **
1511 ** For each term of the vector assignment, append new entries to the
1512 ** expression list pList.  In the case of a subquery on the RHS, append
1513 ** TK_SELECT_COLUMN expressions.
1514 */
1515 ExprList *sqlite3ExprListAppendVector(
1516   Parse *pParse,         /* Parsing context */
1517   ExprList *pList,       /* List to which to append. Might be NULL */
1518   IdList *pColumns,      /* List of names of LHS of the assignment */
1519   Expr *pExpr            /* Vector expression to be appended. Might be NULL */
1520 ){
1521   sqlite3 *db = pParse->db;
1522   int n;
1523   int i;
1524   int iFirst = pList ? pList->nExpr : 0;
1525   /* pColumns can only be NULL due to an OOM but an OOM will cause an
1526   ** exit prior to this routine being invoked */
1527   if( NEVER(pColumns==0) ) goto vector_append_error;
1528   if( pExpr==0 ) goto vector_append_error;
1529 
1530   /* If the RHS is a vector, then we can immediately check to see that
1531   ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
1532   ** wildcards ("*") in the result set of the SELECT must be expanded before
1533   ** we can do the size check, so defer the size check until code generation.
1534   */
1535   if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1536     sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1537                     pColumns->nId, n);
1538     goto vector_append_error;
1539   }
1540 
1541   for(i=0; i<pColumns->nId; i++){
1542     Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1543     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1544     if( pList ){
1545       assert( pList->nExpr==iFirst+i+1 );
1546       pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1547       pColumns->a[i].zName = 0;
1548     }
1549   }
1550 
1551   if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1552     Expr *pFirst = pList->a[iFirst].pExpr;
1553     assert( pFirst!=0 );
1554     assert( pFirst->op==TK_SELECT_COLUMN );
1555 
1556     /* Store the SELECT statement in pRight so it will be deleted when
1557     ** sqlite3ExprListDelete() is called */
1558     pFirst->pRight = pExpr;
1559     pExpr = 0;
1560 
1561     /* Remember the size of the LHS in iTable so that we can check that
1562     ** the RHS and LHS sizes match during code generation. */
1563     pFirst->iTable = pColumns->nId;
1564   }
1565 
1566 vector_append_error:
1567   sqlite3ExprDelete(db, pExpr);
1568   sqlite3IdListDelete(db, pColumns);
1569   return pList;
1570 }
1571 
1572 /*
1573 ** Set the sort order for the last element on the given ExprList.
1574 */
1575 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1576   if( p==0 ) return;
1577   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1578   assert( p->nExpr>0 );
1579   if( iSortOrder<0 ){
1580     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1581     return;
1582   }
1583   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1584 }
1585 
1586 /*
1587 ** Set the ExprList.a[].zName element of the most recently added item
1588 ** on the expression list.
1589 **
1590 ** pList might be NULL following an OOM error.  But pName should never be
1591 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1592 ** is set.
1593 */
1594 void sqlite3ExprListSetName(
1595   Parse *pParse,          /* Parsing context */
1596   ExprList *pList,        /* List to which to add the span. */
1597   Token *pName,           /* Name to be added */
1598   int dequote             /* True to cause the name to be dequoted */
1599 ){
1600   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1601   if( pList ){
1602     struct ExprList_item *pItem;
1603     assert( pList->nExpr>0 );
1604     pItem = &pList->a[pList->nExpr-1];
1605     assert( pItem->zName==0 );
1606     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1607     if( dequote ) sqlite3Dequote(pItem->zName);
1608   }
1609 }
1610 
1611 /*
1612 ** Set the ExprList.a[].zSpan element of the most recently added item
1613 ** on the expression list.
1614 **
1615 ** pList might be NULL following an OOM error.  But pSpan should never be
1616 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1617 ** is set.
1618 */
1619 void sqlite3ExprListSetSpan(
1620   Parse *pParse,          /* Parsing context */
1621   ExprList *pList,        /* List to which to add the span. */
1622   ExprSpan *pSpan         /* The span to be added */
1623 ){
1624   sqlite3 *db = pParse->db;
1625   assert( pList!=0 || db->mallocFailed!=0 );
1626   if( pList ){
1627     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1628     assert( pList->nExpr>0 );
1629     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1630     sqlite3DbFree(db, pItem->zSpan);
1631     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1632                                     (int)(pSpan->zEnd - pSpan->zStart));
1633   }
1634 }
1635 
1636 /*
1637 ** If the expression list pEList contains more than iLimit elements,
1638 ** leave an error message in pParse.
1639 */
1640 void sqlite3ExprListCheckLength(
1641   Parse *pParse,
1642   ExprList *pEList,
1643   const char *zObject
1644 ){
1645   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1646   testcase( pEList && pEList->nExpr==mx );
1647   testcase( pEList && pEList->nExpr==mx+1 );
1648   if( pEList && pEList->nExpr>mx ){
1649     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1650   }
1651 }
1652 
1653 /*
1654 ** Delete an entire expression list.
1655 */
1656 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1657   int i = pList->nExpr;
1658   struct ExprList_item *pItem =  pList->a;
1659   assert( pList->nExpr>0 );
1660   do{
1661     sqlite3ExprDelete(db, pItem->pExpr);
1662     sqlite3DbFree(db, pItem->zName);
1663     sqlite3DbFree(db, pItem->zSpan);
1664     pItem++;
1665   }while( --i>0 );
1666   sqlite3DbFreeNN(db, pList);
1667 }
1668 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1669   if( pList ) exprListDeleteNN(db, pList);
1670 }
1671 
1672 /*
1673 ** Return the bitwise-OR of all Expr.flags fields in the given
1674 ** ExprList.
1675 */
1676 u32 sqlite3ExprListFlags(const ExprList *pList){
1677   int i;
1678   u32 m = 0;
1679   if( pList ){
1680     for(i=0; i<pList->nExpr; i++){
1681        Expr *pExpr = pList->a[i].pExpr;
1682        assert( pExpr!=0 );
1683        m |= pExpr->flags;
1684     }
1685   }
1686   return m;
1687 }
1688 
1689 /*
1690 ** These routines are Walker callbacks used to check expressions to
1691 ** see if they are "constant" for some definition of constant.  The
1692 ** Walker.eCode value determines the type of "constant" we are looking
1693 ** for.
1694 **
1695 ** These callback routines are used to implement the following:
1696 **
1697 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1698 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1699 **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1700 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
1701 **
1702 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1703 ** is found to not be a constant.
1704 **
1705 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1706 ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
1707 ** an existing schema and 4 when processing a new statement.  A bound
1708 ** parameter raises an error for new statements, but is silently converted
1709 ** to NULL for existing schemas.  This allows sqlite_master tables that
1710 ** contain a bound parameter because they were generated by older versions
1711 ** of SQLite to be parsed by newer versions of SQLite without raising a
1712 ** malformed schema error.
1713 */
1714 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1715 
1716   /* If pWalker->eCode is 2 then any term of the expression that comes from
1717   ** the ON or USING clauses of a left join disqualifies the expression
1718   ** from being considered constant. */
1719   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1720     pWalker->eCode = 0;
1721     return WRC_Abort;
1722   }
1723 
1724   switch( pExpr->op ){
1725     /* Consider functions to be constant if all their arguments are constant
1726     ** and either pWalker->eCode==4 or 5 or the function has the
1727     ** SQLITE_FUNC_CONST flag. */
1728     case TK_FUNCTION:
1729       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1730         return WRC_Continue;
1731       }else{
1732         pWalker->eCode = 0;
1733         return WRC_Abort;
1734       }
1735     case TK_ID:
1736     case TK_COLUMN:
1737     case TK_AGG_FUNCTION:
1738     case TK_AGG_COLUMN:
1739       testcase( pExpr->op==TK_ID );
1740       testcase( pExpr->op==TK_COLUMN );
1741       testcase( pExpr->op==TK_AGG_FUNCTION );
1742       testcase( pExpr->op==TK_AGG_COLUMN );
1743       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1744         return WRC_Continue;
1745       }
1746       /* Fall through */
1747     case TK_IF_NULL_ROW:
1748       testcase( pExpr->op==TK_IF_NULL_ROW );
1749       pWalker->eCode = 0;
1750       return WRC_Abort;
1751     case TK_VARIABLE:
1752       if( pWalker->eCode==5 ){
1753         /* Silently convert bound parameters that appear inside of CREATE
1754         ** statements into a NULL when parsing the CREATE statement text out
1755         ** of the sqlite_master table */
1756         pExpr->op = TK_NULL;
1757       }else if( pWalker->eCode==4 ){
1758         /* A bound parameter in a CREATE statement that originates from
1759         ** sqlite3_prepare() causes an error */
1760         pWalker->eCode = 0;
1761         return WRC_Abort;
1762       }
1763       /* Fall through */
1764     default:
1765       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1766       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
1767       return WRC_Continue;
1768   }
1769 }
1770 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1771   UNUSED_PARAMETER(NotUsed);
1772   pWalker->eCode = 0;
1773   return WRC_Abort;
1774 }
1775 static int exprIsConst(Expr *p, int initFlag, int iCur){
1776   Walker w;
1777   w.eCode = initFlag;
1778   w.xExprCallback = exprNodeIsConstant;
1779   w.xSelectCallback = selectNodeIsConstant;
1780 #ifdef SQLITE_DEBUG
1781   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
1782 #endif
1783   w.u.iCur = iCur;
1784   sqlite3WalkExpr(&w, p);
1785   return w.eCode;
1786 }
1787 
1788 /*
1789 ** Walk an expression tree.  Return non-zero if the expression is constant
1790 ** and 0 if it involves variables or function calls.
1791 **
1792 ** For the purposes of this function, a double-quoted string (ex: "abc")
1793 ** is considered a variable but a single-quoted string (ex: 'abc') is
1794 ** a constant.
1795 */
1796 int sqlite3ExprIsConstant(Expr *p){
1797   return exprIsConst(p, 1, 0);
1798 }
1799 
1800 /*
1801 ** Walk an expression tree.  Return non-zero if the expression is constant
1802 ** that does no originate from the ON or USING clauses of a join.
1803 ** Return 0 if it involves variables or function calls or terms from
1804 ** an ON or USING clause.
1805 */
1806 int sqlite3ExprIsConstantNotJoin(Expr *p){
1807   return exprIsConst(p, 2, 0);
1808 }
1809 
1810 /*
1811 ** Walk an expression tree.  Return non-zero if the expression is constant
1812 ** for any single row of the table with cursor iCur.  In other words, the
1813 ** expression must not refer to any non-deterministic function nor any
1814 ** table other than iCur.
1815 */
1816 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1817   return exprIsConst(p, 3, iCur);
1818 }
1819 
1820 
1821 /*
1822 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
1823 */
1824 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
1825   ExprList *pGroupBy = pWalker->u.pGroupBy;
1826   int i;
1827 
1828   /* Check if pExpr is identical to any GROUP BY term. If so, consider
1829   ** it constant.  */
1830   for(i=0; i<pGroupBy->nExpr; i++){
1831     Expr *p = pGroupBy->a[i].pExpr;
1832     if( sqlite3ExprCompare(pExpr, p, -1)<2 ){
1833       CollSeq *pColl = sqlite3ExprCollSeq(pWalker->pParse, p);
1834       if( pColl==0 || sqlite3_stricmp("BINARY", pColl->zName)==0 ){
1835         return WRC_Prune;
1836       }
1837     }
1838   }
1839 
1840   /* Check if pExpr is a sub-select. If so, consider it variable. */
1841   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1842     pWalker->eCode = 0;
1843     return WRC_Abort;
1844   }
1845 
1846   return exprNodeIsConstant(pWalker, pExpr);
1847 }
1848 
1849 /*
1850 ** Walk the expression tree passed as the first argument. Return non-zero
1851 ** if the expression consists entirely of constants or copies of terms
1852 ** in pGroupBy that sort with the BINARY collation sequence.
1853 **
1854 ** This routine is used to determine if a term of the HAVING clause can
1855 ** be promoted into the WHERE clause.  In order for such a promotion to work,
1856 ** the value of the HAVING clause term must be the same for all members of
1857 ** a "group".  The requirement that the GROUP BY term must be BINARY
1858 ** assumes that no other collating sequence will have a finer-grained
1859 ** grouping than binary.  In other words (A=B COLLATE binary) implies
1860 ** A=B in every other collating sequence.  The requirement that the
1861 ** GROUP BY be BINARY is stricter than necessary.  It would also work
1862 ** to promote HAVING clauses that use the same alternative collating
1863 ** sequence as the GROUP BY term, but that is much harder to check,
1864 ** alternative collating sequences are uncommon, and this is only an
1865 ** optimization, so we take the easy way out and simply require the
1866 ** GROUP BY to use the BINARY collating sequence.
1867 */
1868 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
1869   Walker w;
1870   w.eCode = 1;
1871   w.xExprCallback = exprNodeIsConstantOrGroupBy;
1872   w.xSelectCallback = 0;
1873   w.u.pGroupBy = pGroupBy;
1874   w.pParse = pParse;
1875   sqlite3WalkExpr(&w, p);
1876   return w.eCode;
1877 }
1878 
1879 /*
1880 ** Walk an expression tree.  Return non-zero if the expression is constant
1881 ** or a function call with constant arguments.  Return and 0 if there
1882 ** are any variables.
1883 **
1884 ** For the purposes of this function, a double-quoted string (ex: "abc")
1885 ** is considered a variable but a single-quoted string (ex: 'abc') is
1886 ** a constant.
1887 */
1888 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1889   assert( isInit==0 || isInit==1 );
1890   return exprIsConst(p, 4+isInit, 0);
1891 }
1892 
1893 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1894 /*
1895 ** Walk an expression tree.  Return 1 if the expression contains a
1896 ** subquery of some kind.  Return 0 if there are no subqueries.
1897 */
1898 int sqlite3ExprContainsSubquery(Expr *p){
1899   Walker w;
1900   w.eCode = 1;
1901   w.xExprCallback = sqlite3ExprWalkNoop;
1902   w.xSelectCallback = selectNodeIsConstant;
1903 #ifdef SQLITE_DEBUG
1904   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
1905 #endif
1906   sqlite3WalkExpr(&w, p);
1907   return w.eCode==0;
1908 }
1909 #endif
1910 
1911 /*
1912 ** If the expression p codes a constant integer that is small enough
1913 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1914 ** in *pValue.  If the expression is not an integer or if it is too big
1915 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1916 */
1917 int sqlite3ExprIsInteger(Expr *p, int *pValue){
1918   int rc = 0;
1919   if( p==0 ) return 0;  /* Can only happen following on OOM */
1920 
1921   /* If an expression is an integer literal that fits in a signed 32-bit
1922   ** integer, then the EP_IntValue flag will have already been set */
1923   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1924            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1925 
1926   if( p->flags & EP_IntValue ){
1927     *pValue = p->u.iValue;
1928     return 1;
1929   }
1930   switch( p->op ){
1931     case TK_UPLUS: {
1932       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1933       break;
1934     }
1935     case TK_UMINUS: {
1936       int v;
1937       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1938         assert( v!=(-2147483647-1) );
1939         *pValue = -v;
1940         rc = 1;
1941       }
1942       break;
1943     }
1944     default: break;
1945   }
1946   return rc;
1947 }
1948 
1949 /*
1950 ** Return FALSE if there is no chance that the expression can be NULL.
1951 **
1952 ** If the expression might be NULL or if the expression is too complex
1953 ** to tell return TRUE.
1954 **
1955 ** This routine is used as an optimization, to skip OP_IsNull opcodes
1956 ** when we know that a value cannot be NULL.  Hence, a false positive
1957 ** (returning TRUE when in fact the expression can never be NULL) might
1958 ** be a small performance hit but is otherwise harmless.  On the other
1959 ** hand, a false negative (returning FALSE when the result could be NULL)
1960 ** will likely result in an incorrect answer.  So when in doubt, return
1961 ** TRUE.
1962 */
1963 int sqlite3ExprCanBeNull(const Expr *p){
1964   u8 op;
1965   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1966   op = p->op;
1967   if( op==TK_REGISTER ) op = p->op2;
1968   switch( op ){
1969     case TK_INTEGER:
1970     case TK_STRING:
1971     case TK_FLOAT:
1972     case TK_BLOB:
1973       return 0;
1974     case TK_COLUMN:
1975       assert( p->pTab!=0 );
1976       return ExprHasProperty(p, EP_CanBeNull) ||
1977              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
1978     default:
1979       return 1;
1980   }
1981 }
1982 
1983 /*
1984 ** Return TRUE if the given expression is a constant which would be
1985 ** unchanged by OP_Affinity with the affinity given in the second
1986 ** argument.
1987 **
1988 ** This routine is used to determine if the OP_Affinity operation
1989 ** can be omitted.  When in doubt return FALSE.  A false negative
1990 ** is harmless.  A false positive, however, can result in the wrong
1991 ** answer.
1992 */
1993 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1994   u8 op;
1995   if( aff==SQLITE_AFF_BLOB ) return 1;
1996   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1997   op = p->op;
1998   if( op==TK_REGISTER ) op = p->op2;
1999   switch( op ){
2000     case TK_INTEGER: {
2001       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
2002     }
2003     case TK_FLOAT: {
2004       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
2005     }
2006     case TK_STRING: {
2007       return aff==SQLITE_AFF_TEXT;
2008     }
2009     case TK_BLOB: {
2010       return 1;
2011     }
2012     case TK_COLUMN: {
2013       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
2014       return p->iColumn<0
2015           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
2016     }
2017     default: {
2018       return 0;
2019     }
2020   }
2021 }
2022 
2023 /*
2024 ** Return TRUE if the given string is a row-id column name.
2025 */
2026 int sqlite3IsRowid(const char *z){
2027   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2028   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2029   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2030   return 0;
2031 }
2032 
2033 /*
2034 ** pX is the RHS of an IN operator.  If pX is a SELECT statement
2035 ** that can be simplified to a direct table access, then return
2036 ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
2037 ** or if the SELECT statement needs to be manifested into a transient
2038 ** table, then return NULL.
2039 */
2040 #ifndef SQLITE_OMIT_SUBQUERY
2041 static Select *isCandidateForInOpt(Expr *pX){
2042   Select *p;
2043   SrcList *pSrc;
2044   ExprList *pEList;
2045   Table *pTab;
2046   int i;
2047   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
2048   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
2049   p = pX->x.pSelect;
2050   if( p->pPrior ) return 0;              /* Not a compound SELECT */
2051   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2052     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2053     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2054     return 0; /* No DISTINCT keyword and no aggregate functions */
2055   }
2056   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
2057   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
2058   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
2059   if( p->pWhere ) return 0;              /* Has no WHERE clause */
2060   pSrc = p->pSrc;
2061   assert( pSrc!=0 );
2062   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
2063   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
2064   pTab = pSrc->a[0].pTab;
2065   assert( pTab!=0 );
2066   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
2067   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
2068   pEList = p->pEList;
2069   assert( pEList!=0 );
2070   /* All SELECT results must be columns. */
2071   for(i=0; i<pEList->nExpr; i++){
2072     Expr *pRes = pEList->a[i].pExpr;
2073     if( pRes->op!=TK_COLUMN ) return 0;
2074     assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
2075   }
2076   return p;
2077 }
2078 #endif /* SQLITE_OMIT_SUBQUERY */
2079 
2080 #ifndef SQLITE_OMIT_SUBQUERY
2081 /*
2082 ** Generate code that checks the left-most column of index table iCur to see if
2083 ** it contains any NULL entries.  Cause the register at regHasNull to be set
2084 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
2085 ** to be set to NULL if iCur contains one or more NULL values.
2086 */
2087 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2088   int addr1;
2089   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2090   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2091   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2092   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2093   VdbeComment((v, "first_entry_in(%d)", iCur));
2094   sqlite3VdbeJumpHere(v, addr1);
2095 }
2096 #endif
2097 
2098 
2099 #ifndef SQLITE_OMIT_SUBQUERY
2100 /*
2101 ** The argument is an IN operator with a list (not a subquery) on the
2102 ** right-hand side.  Return TRUE if that list is constant.
2103 */
2104 static int sqlite3InRhsIsConstant(Expr *pIn){
2105   Expr *pLHS;
2106   int res;
2107   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2108   pLHS = pIn->pLeft;
2109   pIn->pLeft = 0;
2110   res = sqlite3ExprIsConstant(pIn);
2111   pIn->pLeft = pLHS;
2112   return res;
2113 }
2114 #endif
2115 
2116 /*
2117 ** This function is used by the implementation of the IN (...) operator.
2118 ** The pX parameter is the expression on the RHS of the IN operator, which
2119 ** might be either a list of expressions or a subquery.
2120 **
2121 ** The job of this routine is to find or create a b-tree object that can
2122 ** be used either to test for membership in the RHS set or to iterate through
2123 ** all members of the RHS set, skipping duplicates.
2124 **
2125 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2126 ** and pX->iTable is set to the index of that cursor.
2127 **
2128 ** The returned value of this function indicates the b-tree type, as follows:
2129 **
2130 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
2131 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
2132 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2133 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
2134 **                         populated epheremal table.
2135 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
2136 **                         implemented as a sequence of comparisons.
2137 **
2138 ** An existing b-tree might be used if the RHS expression pX is a simple
2139 ** subquery such as:
2140 **
2141 **     SELECT <column1>, <column2>... FROM <table>
2142 **
2143 ** If the RHS of the IN operator is a list or a more complex subquery, then
2144 ** an ephemeral table might need to be generated from the RHS and then
2145 ** pX->iTable made to point to the ephemeral table instead of an
2146 ** existing table.
2147 **
2148 ** The inFlags parameter must contain exactly one of the bits
2149 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
2150 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2151 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
2152 ** IN index will be used to loop over all values of the RHS of the
2153 ** IN operator.
2154 **
2155 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2156 ** through the set members) then the b-tree must not contain duplicates.
2157 ** An epheremal table must be used unless the selected columns are guaranteed
2158 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2159 ** a UNIQUE constraint or index.
2160 **
2161 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2162 ** for fast set membership tests) then an epheremal table must
2163 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2164 ** index can be found with the specified <columns> as its left-most.
2165 **
2166 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2167 ** if the RHS of the IN operator is a list (not a subquery) then this
2168 ** routine might decide that creating an ephemeral b-tree for membership
2169 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
2170 ** calling routine should implement the IN operator using a sequence
2171 ** of Eq or Ne comparison operations.
2172 **
2173 ** When the b-tree is being used for membership tests, the calling function
2174 ** might need to know whether or not the RHS side of the IN operator
2175 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
2176 ** if there is any chance that the (...) might contain a NULL value at
2177 ** runtime, then a register is allocated and the register number written
2178 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2179 ** NULL value, then *prRhsHasNull is left unchanged.
2180 **
2181 ** If a register is allocated and its location stored in *prRhsHasNull, then
2182 ** the value in that register will be NULL if the b-tree contains one or more
2183 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2184 ** NULL values.
2185 **
2186 ** If the aiMap parameter is not NULL, it must point to an array containing
2187 ** one element for each column returned by the SELECT statement on the RHS
2188 ** of the IN(...) operator. The i'th entry of the array is populated with the
2189 ** offset of the index column that matches the i'th column returned by the
2190 ** SELECT. For example, if the expression and selected index are:
2191 **
2192 **   (?,?,?) IN (SELECT a, b, c FROM t1)
2193 **   CREATE INDEX i1 ON t1(b, c, a);
2194 **
2195 ** then aiMap[] is populated with {2, 0, 1}.
2196 */
2197 #ifndef SQLITE_OMIT_SUBQUERY
2198 int sqlite3FindInIndex(
2199   Parse *pParse,             /* Parsing context */
2200   Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
2201   u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2202   int *prRhsHasNull,         /* Register holding NULL status.  See notes */
2203   int *aiMap                 /* Mapping from Index fields to RHS fields */
2204 ){
2205   Select *p;                            /* SELECT to the right of IN operator */
2206   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
2207   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
2208   int mustBeUnique;                     /* True if RHS must be unique */
2209   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
2210 
2211   assert( pX->op==TK_IN );
2212   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2213 
2214   /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2215   ** whether or not the SELECT result contains NULL values, check whether
2216   ** or not NULL is actually possible (it may not be, for example, due
2217   ** to NOT NULL constraints in the schema). If no NULL values are possible,
2218   ** set prRhsHasNull to 0 before continuing.  */
2219   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2220     int i;
2221     ExprList *pEList = pX->x.pSelect->pEList;
2222     for(i=0; i<pEList->nExpr; i++){
2223       if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2224     }
2225     if( i==pEList->nExpr ){
2226       prRhsHasNull = 0;
2227     }
2228   }
2229 
2230   /* Check to see if an existing table or index can be used to
2231   ** satisfy the query.  This is preferable to generating a new
2232   ** ephemeral table.  */
2233   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2234     sqlite3 *db = pParse->db;              /* Database connection */
2235     Table *pTab;                           /* Table <table>. */
2236     i16 iDb;                               /* Database idx for pTab */
2237     ExprList *pEList = p->pEList;
2238     int nExpr = pEList->nExpr;
2239 
2240     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
2241     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2242     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
2243     pTab = p->pSrc->a[0].pTab;
2244 
2245     /* Code an OP_Transaction and OP_TableLock for <table>. */
2246     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2247     sqlite3CodeVerifySchema(pParse, iDb);
2248     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2249 
2250     assert(v);  /* sqlite3GetVdbe() has always been previously called */
2251     if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2252       /* The "x IN (SELECT rowid FROM table)" case */
2253       int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2254       VdbeCoverage(v);
2255 
2256       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2257       eType = IN_INDEX_ROWID;
2258 
2259       sqlite3VdbeJumpHere(v, iAddr);
2260     }else{
2261       Index *pIdx;                         /* Iterator variable */
2262       int affinity_ok = 1;
2263       int i;
2264 
2265       /* Check that the affinity that will be used to perform each
2266       ** comparison is the same as the affinity of each column in table
2267       ** on the RHS of the IN operator.  If it not, it is not possible to
2268       ** use any index of the RHS table.  */
2269       for(i=0; i<nExpr && affinity_ok; i++){
2270         Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2271         int iCol = pEList->a[i].pExpr->iColumn;
2272         char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2273         char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2274         testcase( cmpaff==SQLITE_AFF_BLOB );
2275         testcase( cmpaff==SQLITE_AFF_TEXT );
2276         switch( cmpaff ){
2277           case SQLITE_AFF_BLOB:
2278             break;
2279           case SQLITE_AFF_TEXT:
2280             /* sqlite3CompareAffinity() only returns TEXT if one side or the
2281             ** other has no affinity and the other side is TEXT.  Hence,
2282             ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2283             ** and for the term on the LHS of the IN to have no affinity. */
2284             assert( idxaff==SQLITE_AFF_TEXT );
2285             break;
2286           default:
2287             affinity_ok = sqlite3IsNumericAffinity(idxaff);
2288         }
2289       }
2290 
2291       if( affinity_ok ){
2292         /* Search for an existing index that will work for this IN operator */
2293         for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2294           Bitmask colUsed;      /* Columns of the index used */
2295           Bitmask mCol;         /* Mask for the current column */
2296           if( pIdx->nColumn<nExpr ) continue;
2297           /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2298           ** BITMASK(nExpr) without overflowing */
2299           testcase( pIdx->nColumn==BMS-2 );
2300           testcase( pIdx->nColumn==BMS-1 );
2301           if( pIdx->nColumn>=BMS-1 ) continue;
2302           if( mustBeUnique ){
2303             if( pIdx->nKeyCol>nExpr
2304              ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2305             ){
2306               continue;  /* This index is not unique over the IN RHS columns */
2307             }
2308           }
2309 
2310           colUsed = 0;   /* Columns of index used so far */
2311           for(i=0; i<nExpr; i++){
2312             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2313             Expr *pRhs = pEList->a[i].pExpr;
2314             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2315             int j;
2316 
2317             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2318             for(j=0; j<nExpr; j++){
2319               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2320               assert( pIdx->azColl[j] );
2321               if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2322                 continue;
2323               }
2324               break;
2325             }
2326             if( j==nExpr ) break;
2327             mCol = MASKBIT(j);
2328             if( mCol & colUsed ) break; /* Each column used only once */
2329             colUsed |= mCol;
2330             if( aiMap ) aiMap[i] = j;
2331           }
2332 
2333           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2334           if( colUsed==(MASKBIT(nExpr)-1) ){
2335             /* If we reach this point, that means the index pIdx is usable */
2336             int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2337 #ifndef SQLITE_OMIT_EXPLAIN
2338             sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
2339               sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
2340               P4_DYNAMIC);
2341 #endif
2342             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2343             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2344             VdbeComment((v, "%s", pIdx->zName));
2345             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2346             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2347 
2348             if( prRhsHasNull ){
2349 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2350               i64 mask = (1<<nExpr)-1;
2351               sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2352                   iTab, 0, 0, (u8*)&mask, P4_INT64);
2353 #endif
2354               *prRhsHasNull = ++pParse->nMem;
2355               if( nExpr==1 ){
2356                 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2357               }
2358             }
2359             sqlite3VdbeJumpHere(v, iAddr);
2360           }
2361         } /* End loop over indexes */
2362       } /* End if( affinity_ok ) */
2363     } /* End if not an rowid index */
2364   } /* End attempt to optimize using an index */
2365 
2366   /* If no preexisting index is available for the IN clause
2367   ** and IN_INDEX_NOOP is an allowed reply
2368   ** and the RHS of the IN operator is a list, not a subquery
2369   ** and the RHS is not constant or has two or fewer terms,
2370   ** then it is not worth creating an ephemeral table to evaluate
2371   ** the IN operator so return IN_INDEX_NOOP.
2372   */
2373   if( eType==0
2374    && (inFlags & IN_INDEX_NOOP_OK)
2375    && !ExprHasProperty(pX, EP_xIsSelect)
2376    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2377   ){
2378     eType = IN_INDEX_NOOP;
2379   }
2380 
2381   if( eType==0 ){
2382     /* Could not find an existing table or index to use as the RHS b-tree.
2383     ** We will have to generate an ephemeral table to do the job.
2384     */
2385     u32 savedNQueryLoop = pParse->nQueryLoop;
2386     int rMayHaveNull = 0;
2387     eType = IN_INDEX_EPH;
2388     if( inFlags & IN_INDEX_LOOP ){
2389       pParse->nQueryLoop = 0;
2390       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
2391         eType = IN_INDEX_ROWID;
2392       }
2393     }else if( prRhsHasNull ){
2394       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2395     }
2396     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
2397     pParse->nQueryLoop = savedNQueryLoop;
2398   }else{
2399     pX->iTable = iTab;
2400   }
2401 
2402   if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2403     int i, n;
2404     n = sqlite3ExprVectorSize(pX->pLeft);
2405     for(i=0; i<n; i++) aiMap[i] = i;
2406   }
2407   return eType;
2408 }
2409 #endif
2410 
2411 #ifndef SQLITE_OMIT_SUBQUERY
2412 /*
2413 ** Argument pExpr is an (?, ?...) IN(...) expression. This
2414 ** function allocates and returns a nul-terminated string containing
2415 ** the affinities to be used for each column of the comparison.
2416 **
2417 ** It is the responsibility of the caller to ensure that the returned
2418 ** string is eventually freed using sqlite3DbFree().
2419 */
2420 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2421   Expr *pLeft = pExpr->pLeft;
2422   int nVal = sqlite3ExprVectorSize(pLeft);
2423   Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
2424   char *zRet;
2425 
2426   assert( pExpr->op==TK_IN );
2427   zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
2428   if( zRet ){
2429     int i;
2430     for(i=0; i<nVal; i++){
2431       Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2432       char a = sqlite3ExprAffinity(pA);
2433       if( pSelect ){
2434         zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2435       }else{
2436         zRet[i] = a;
2437       }
2438     }
2439     zRet[nVal] = '\0';
2440   }
2441   return zRet;
2442 }
2443 #endif
2444 
2445 #ifndef SQLITE_OMIT_SUBQUERY
2446 /*
2447 ** Load the Parse object passed as the first argument with an error
2448 ** message of the form:
2449 **
2450 **   "sub-select returns N columns - expected M"
2451 */
2452 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2453   const char *zFmt = "sub-select returns %d columns - expected %d";
2454   sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2455 }
2456 #endif
2457 
2458 /*
2459 ** Expression pExpr is a vector that has been used in a context where
2460 ** it is not permitted. If pExpr is a sub-select vector, this routine
2461 ** loads the Parse object with a message of the form:
2462 **
2463 **   "sub-select returns N columns - expected 1"
2464 **
2465 ** Or, if it is a regular scalar vector:
2466 **
2467 **   "row value misused"
2468 */
2469 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2470 #ifndef SQLITE_OMIT_SUBQUERY
2471   if( pExpr->flags & EP_xIsSelect ){
2472     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2473   }else
2474 #endif
2475   {
2476     sqlite3ErrorMsg(pParse, "row value misused");
2477   }
2478 }
2479 
2480 /*
2481 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2482 ** or IN operators.  Examples:
2483 **
2484 **     (SELECT a FROM b)          -- subquery
2485 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
2486 **     x IN (4,5,11)              -- IN operator with list on right-hand side
2487 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
2488 **
2489 ** The pExpr parameter describes the expression that contains the IN
2490 ** operator or subquery.
2491 **
2492 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2493 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2494 ** to some integer key column of a table B-Tree. In this case, use an
2495 ** intkey B-Tree to store the set of IN(...) values instead of the usual
2496 ** (slower) variable length keys B-Tree.
2497 **
2498 ** If rMayHaveNull is non-zero, that means that the operation is an IN
2499 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
2500 ** All this routine does is initialize the register given by rMayHaveNull
2501 ** to NULL.  Calling routines will take care of changing this register
2502 ** value to non-NULL if the RHS is NULL-free.
2503 **
2504 ** For a SELECT or EXISTS operator, return the register that holds the
2505 ** result.  For a multi-column SELECT, the result is stored in a contiguous
2506 ** array of registers and the return value is the register of the left-most
2507 ** result column.  Return 0 for IN operators or if an error occurs.
2508 */
2509 #ifndef SQLITE_OMIT_SUBQUERY
2510 int sqlite3CodeSubselect(
2511   Parse *pParse,          /* Parsing context */
2512   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
2513   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
2514   int isRowid             /* If true, LHS of IN operator is a rowid */
2515 ){
2516   int jmpIfDynamic = -1;                      /* One-time test address */
2517   int rReg = 0;                           /* Register storing resulting */
2518   Vdbe *v = sqlite3GetVdbe(pParse);
2519   if( NEVER(v==0) ) return 0;
2520   sqlite3ExprCachePush(pParse);
2521 
2522   /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2523   ** is encountered if any of the following is true:
2524   **
2525   **    *  The right-hand side is a correlated subquery
2526   **    *  The right-hand side is an expression list containing variables
2527   **    *  We are inside a trigger
2528   **
2529   ** If all of the above are false, then we can run this code just once
2530   ** save the results, and reuse the same result on subsequent invocations.
2531   */
2532   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
2533     jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2534   }
2535 
2536 #ifndef SQLITE_OMIT_EXPLAIN
2537   if( pParse->explain==2 ){
2538     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2539         jmpIfDynamic>=0?"":"CORRELATED ",
2540         pExpr->op==TK_IN?"LIST":"SCALAR",
2541         pParse->iNextSelectId
2542     );
2543     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2544   }
2545 #endif
2546 
2547   switch( pExpr->op ){
2548     case TK_IN: {
2549       int addr;                   /* Address of OP_OpenEphemeral instruction */
2550       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
2551       KeyInfo *pKeyInfo = 0;      /* Key information */
2552       int nVal;                   /* Size of vector pLeft */
2553 
2554       nVal = sqlite3ExprVectorSize(pLeft);
2555       assert( !isRowid || nVal==1 );
2556 
2557       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
2558       ** expression it is handled the same way.  An ephemeral table is
2559       ** filled with index keys representing the results from the
2560       ** SELECT or the <exprlist>.
2561       **
2562       ** If the 'x' expression is a column value, or the SELECT...
2563       ** statement returns a column value, then the affinity of that
2564       ** column is used to build the index keys. If both 'x' and the
2565       ** SELECT... statement are columns, then numeric affinity is used
2566       ** if either column has NUMERIC or INTEGER affinity. If neither
2567       ** 'x' nor the SELECT... statement are columns, then numeric affinity
2568       ** is used.
2569       */
2570       pExpr->iTable = pParse->nTab++;
2571       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2572           pExpr->iTable, (isRowid?0:nVal));
2573       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2574 
2575       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2576         /* Case 1:     expr IN (SELECT ...)
2577         **
2578         ** Generate code to write the results of the select into the temporary
2579         ** table allocated and opened above.
2580         */
2581         Select *pSelect = pExpr->x.pSelect;
2582         ExprList *pEList = pSelect->pEList;
2583 
2584         assert( !isRowid );
2585         /* If the LHS and RHS of the IN operator do not match, that
2586         ** error will have been caught long before we reach this point. */
2587         if( ALWAYS(pEList->nExpr==nVal) ){
2588           SelectDest dest;
2589           int i;
2590           sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2591           dest.zAffSdst = exprINAffinity(pParse, pExpr);
2592           pSelect->iLimit = 0;
2593           testcase( pSelect->selFlags & SF_Distinct );
2594           testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2595           if( sqlite3Select(pParse, pSelect, &dest) ){
2596             sqlite3DbFree(pParse->db, dest.zAffSdst);
2597             sqlite3KeyInfoUnref(pKeyInfo);
2598             return 0;
2599           }
2600           sqlite3DbFree(pParse->db, dest.zAffSdst);
2601           assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2602           assert( pEList!=0 );
2603           assert( pEList->nExpr>0 );
2604           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2605           for(i=0; i<nVal; i++){
2606             Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
2607             pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2608                 pParse, p, pEList->a[i].pExpr
2609             );
2610           }
2611         }
2612       }else if( ALWAYS(pExpr->x.pList!=0) ){
2613         /* Case 2:     expr IN (exprlist)
2614         **
2615         ** For each expression, build an index key from the evaluation and
2616         ** store it in the temporary table. If <expr> is a column, then use
2617         ** that columns affinity when building index keys. If <expr> is not
2618         ** a column, use numeric affinity.
2619         */
2620         char affinity;            /* Affinity of the LHS of the IN */
2621         int i;
2622         ExprList *pList = pExpr->x.pList;
2623         struct ExprList_item *pItem;
2624         int r1, r2, r3;
2625 
2626         affinity = sqlite3ExprAffinity(pLeft);
2627         if( !affinity ){
2628           affinity = SQLITE_AFF_BLOB;
2629         }
2630         if( pKeyInfo ){
2631           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2632           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2633         }
2634 
2635         /* Loop through each expression in <exprlist>. */
2636         r1 = sqlite3GetTempReg(pParse);
2637         r2 = sqlite3GetTempReg(pParse);
2638         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
2639         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2640           Expr *pE2 = pItem->pExpr;
2641           int iValToIns;
2642 
2643           /* If the expression is not constant then we will need to
2644           ** disable the test that was generated above that makes sure
2645           ** this code only executes once.  Because for a non-constant
2646           ** expression we need to rerun this code each time.
2647           */
2648           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2649             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2650             jmpIfDynamic = -1;
2651           }
2652 
2653           /* Evaluate the expression and insert it into the temp table */
2654           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2655             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
2656           }else{
2657             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2658             if( isRowid ){
2659               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2660                                 sqlite3VdbeCurrentAddr(v)+2);
2661               VdbeCoverage(v);
2662               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2663             }else{
2664               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2665               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2666               sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
2667             }
2668           }
2669         }
2670         sqlite3ReleaseTempReg(pParse, r1);
2671         sqlite3ReleaseTempReg(pParse, r2);
2672       }
2673       if( pKeyInfo ){
2674         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
2675       }
2676       break;
2677     }
2678 
2679     case TK_EXISTS:
2680     case TK_SELECT:
2681     default: {
2682       /* Case 3:    (SELECT ... FROM ...)
2683       **     or:    EXISTS(SELECT ... FROM ...)
2684       **
2685       ** For a SELECT, generate code to put the values for all columns of
2686       ** the first row into an array of registers and return the index of
2687       ** the first register.
2688       **
2689       ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2690       ** into a register and return that register number.
2691       **
2692       ** In both cases, the query is augmented with "LIMIT 1".  Any
2693       ** preexisting limit is discarded in place of the new LIMIT 1.
2694       */
2695       Select *pSel;                         /* SELECT statement to encode */
2696       SelectDest dest;                      /* How to deal with SELECT result */
2697       int nReg;                             /* Registers to allocate */
2698 
2699       testcase( pExpr->op==TK_EXISTS );
2700       testcase( pExpr->op==TK_SELECT );
2701       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2702       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
2703 
2704       pSel = pExpr->x.pSelect;
2705       nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2706       sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2707       pParse->nMem += nReg;
2708       if( pExpr->op==TK_SELECT ){
2709         dest.eDest = SRT_Mem;
2710         dest.iSdst = dest.iSDParm;
2711         dest.nSdst = nReg;
2712         sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
2713         VdbeComment((v, "Init subquery result"));
2714       }else{
2715         dest.eDest = SRT_Exists;
2716         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2717         VdbeComment((v, "Init EXISTS result"));
2718       }
2719       sqlite3ExprDelete(pParse->db, pSel->pLimit);
2720       pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
2721                                   &sqlite3IntTokens[1], 0);
2722       pSel->iLimit = 0;
2723       pSel->selFlags &= ~SF_MultiValue;
2724       if( sqlite3Select(pParse, pSel, &dest) ){
2725         return 0;
2726       }
2727       rReg = dest.iSDParm;
2728       ExprSetVVAProperty(pExpr, EP_NoReduce);
2729       break;
2730     }
2731   }
2732 
2733   if( rHasNullFlag ){
2734     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
2735   }
2736 
2737   if( jmpIfDynamic>=0 ){
2738     sqlite3VdbeJumpHere(v, jmpIfDynamic);
2739   }
2740   sqlite3ExprCachePop(pParse);
2741 
2742   return rReg;
2743 }
2744 #endif /* SQLITE_OMIT_SUBQUERY */
2745 
2746 #ifndef SQLITE_OMIT_SUBQUERY
2747 /*
2748 ** Expr pIn is an IN(...) expression. This function checks that the
2749 ** sub-select on the RHS of the IN() operator has the same number of
2750 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2751 ** a sub-query, that the LHS is a vector of size 1.
2752 */
2753 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2754   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2755   if( (pIn->flags & EP_xIsSelect) ){
2756     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2757       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2758       return 1;
2759     }
2760   }else if( nVector!=1 ){
2761     sqlite3VectorErrorMsg(pParse, pIn->pLeft);
2762     return 1;
2763   }
2764   return 0;
2765 }
2766 #endif
2767 
2768 #ifndef SQLITE_OMIT_SUBQUERY
2769 /*
2770 ** Generate code for an IN expression.
2771 **
2772 **      x IN (SELECT ...)
2773 **      x IN (value, value, ...)
2774 **
2775 ** The left-hand side (LHS) is a scalar or vector expression.  The
2776 ** right-hand side (RHS) is an array of zero or more scalar values, or a
2777 ** subquery.  If the RHS is a subquery, the number of result columns must
2778 ** match the number of columns in the vector on the LHS.  If the RHS is
2779 ** a list of values, the LHS must be a scalar.
2780 **
2781 ** The IN operator is true if the LHS value is contained within the RHS.
2782 ** The result is false if the LHS is definitely not in the RHS.  The
2783 ** result is NULL if the presence of the LHS in the RHS cannot be
2784 ** determined due to NULLs.
2785 **
2786 ** This routine generates code that jumps to destIfFalse if the LHS is not
2787 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
2788 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
2789 ** within the RHS then fall through.
2790 **
2791 ** See the separate in-operator.md documentation file in the canonical
2792 ** SQLite source tree for additional information.
2793 */
2794 static void sqlite3ExprCodeIN(
2795   Parse *pParse,        /* Parsing and code generating context */
2796   Expr *pExpr,          /* The IN expression */
2797   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
2798   int destIfNull        /* Jump here if the results are unknown due to NULLs */
2799 ){
2800   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
2801   int eType;            /* Type of the RHS */
2802   int rLhs;             /* Register(s) holding the LHS values */
2803   int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
2804   Vdbe *v;              /* Statement under construction */
2805   int *aiMap = 0;       /* Map from vector field to index column */
2806   char *zAff = 0;       /* Affinity string for comparisons */
2807   int nVector;          /* Size of vectors for this IN operator */
2808   int iDummy;           /* Dummy parameter to exprCodeVector() */
2809   Expr *pLeft;          /* The LHS of the IN operator */
2810   int i;                /* loop counter */
2811   int destStep2;        /* Where to jump when NULLs seen in step 2 */
2812   int destStep6 = 0;    /* Start of code for Step 6 */
2813   int addrTruthOp;      /* Address of opcode that determines the IN is true */
2814   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
2815   int addrTop;          /* Top of the step-6 loop */
2816 
2817   pLeft = pExpr->pLeft;
2818   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
2819   zAff = exprINAffinity(pParse, pExpr);
2820   nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2821   aiMap = (int*)sqlite3DbMallocZero(
2822       pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2823   );
2824   if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
2825 
2826   /* Attempt to compute the RHS. After this step, if anything other than
2827   ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2828   ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2829   ** the RHS has not yet been coded.  */
2830   v = pParse->pVdbe;
2831   assert( v!=0 );       /* OOM detected prior to this routine */
2832   VdbeNoopComment((v, "begin IN expr"));
2833   eType = sqlite3FindInIndex(pParse, pExpr,
2834                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
2835                              destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
2836 
2837   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2838        || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2839   );
2840 #ifdef SQLITE_DEBUG
2841   /* Confirm that aiMap[] contains nVector integer values between 0 and
2842   ** nVector-1. */
2843   for(i=0; i<nVector; i++){
2844     int j, cnt;
2845     for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
2846     assert( cnt==1 );
2847   }
2848 #endif
2849 
2850   /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2851   ** vector, then it is stored in an array of nVector registers starting
2852   ** at r1.
2853   **
2854   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
2855   ** so that the fields are in the same order as an existing index.   The
2856   ** aiMap[] array contains a mapping from the original LHS field order to
2857   ** the field order that matches the RHS index.
2858   */
2859   sqlite3ExprCachePush(pParse);
2860   rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
2861   for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
2862   if( i==nVector ){
2863     /* LHS fields are not reordered */
2864     rLhs = rLhsOrig;
2865   }else{
2866     /* Need to reorder the LHS fields according to aiMap */
2867     rLhs = sqlite3GetTempRange(pParse, nVector);
2868     for(i=0; i<nVector; i++){
2869       sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
2870     }
2871   }
2872 
2873   /* If sqlite3FindInIndex() did not find or create an index that is
2874   ** suitable for evaluating the IN operator, then evaluate using a
2875   ** sequence of comparisons.
2876   **
2877   ** This is step (1) in the in-operator.md optimized algorithm.
2878   */
2879   if( eType==IN_INDEX_NOOP ){
2880     ExprList *pList = pExpr->x.pList;
2881     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2882     int labelOk = sqlite3VdbeMakeLabel(v);
2883     int r2, regToFree;
2884     int regCkNull = 0;
2885     int ii;
2886     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2887     if( destIfNull!=destIfFalse ){
2888       regCkNull = sqlite3GetTempReg(pParse);
2889       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
2890     }
2891     for(ii=0; ii<pList->nExpr; ii++){
2892       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
2893       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
2894         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2895       }
2896       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2897         sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
2898                           (void*)pColl, P4_COLLSEQ);
2899         VdbeCoverageIf(v, ii<pList->nExpr-1);
2900         VdbeCoverageIf(v, ii==pList->nExpr-1);
2901         sqlite3VdbeChangeP5(v, zAff[0]);
2902       }else{
2903         assert( destIfNull==destIfFalse );
2904         sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
2905                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2906         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
2907       }
2908       sqlite3ReleaseTempReg(pParse, regToFree);
2909     }
2910     if( regCkNull ){
2911       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
2912       sqlite3VdbeGoto(v, destIfFalse);
2913     }
2914     sqlite3VdbeResolveLabel(v, labelOk);
2915     sqlite3ReleaseTempReg(pParse, regCkNull);
2916     goto sqlite3ExprCodeIN_finished;
2917   }
2918 
2919   /* Step 2: Check to see if the LHS contains any NULL columns.  If the
2920   ** LHS does contain NULLs then the result must be either FALSE or NULL.
2921   ** We will then skip the binary search of the RHS.
2922   */
2923   if( destIfNull==destIfFalse ){
2924     destStep2 = destIfFalse;
2925   }else{
2926     destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
2927   }
2928   for(i=0; i<nVector; i++){
2929     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
2930     if( sqlite3ExprCanBeNull(p) ){
2931       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
2932       VdbeCoverage(v);
2933     }
2934   }
2935 
2936   /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
2937   ** of the RHS using the LHS as a probe.  If found, the result is
2938   ** true.
2939   */
2940   if( eType==IN_INDEX_ROWID ){
2941     /* In this case, the RHS is the ROWID of table b-tree and so we also
2942     ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
2943     ** into a single opcode. */
2944     sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
2945     VdbeCoverage(v);
2946     addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
2947   }else{
2948     sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
2949     if( destIfFalse==destIfNull ){
2950       /* Combine Step 3 and Step 5 into a single opcode */
2951       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
2952                            rLhs, nVector); VdbeCoverage(v);
2953       goto sqlite3ExprCodeIN_finished;
2954     }
2955     /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
2956     addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
2957                                       rLhs, nVector); VdbeCoverage(v);
2958   }
2959 
2960   /* Step 4.  If the RHS is known to be non-NULL and we did not find
2961   ** an match on the search above, then the result must be FALSE.
2962   */
2963   if( rRhsHasNull && nVector==1 ){
2964     sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
2965     VdbeCoverage(v);
2966   }
2967 
2968   /* Step 5.  If we do not care about the difference between NULL and
2969   ** FALSE, then just return false.
2970   */
2971   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
2972 
2973   /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
2974   ** If any comparison is NULL, then the result is NULL.  If all
2975   ** comparisons are FALSE then the final result is FALSE.
2976   **
2977   ** For a scalar LHS, it is sufficient to check just the first row
2978   ** of the RHS.
2979   */
2980   if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
2981   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2982   VdbeCoverage(v);
2983   if( nVector>1 ){
2984     destNotNull = sqlite3VdbeMakeLabel(v);
2985   }else{
2986     /* For nVector==1, combine steps 6 and 7 by immediately returning
2987     ** FALSE if the first comparison is not NULL */
2988     destNotNull = destIfFalse;
2989   }
2990   for(i=0; i<nVector; i++){
2991     Expr *p;
2992     CollSeq *pColl;
2993     int r3 = sqlite3GetTempReg(pParse);
2994     p = sqlite3VectorFieldSubexpr(pLeft, i);
2995     pColl = sqlite3ExprCollSeq(pParse, p);
2996     sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
2997     sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
2998                       (void*)pColl, P4_COLLSEQ);
2999     VdbeCoverage(v);
3000     sqlite3ReleaseTempReg(pParse, r3);
3001   }
3002   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3003   if( nVector>1 ){
3004     sqlite3VdbeResolveLabel(v, destNotNull);
3005     sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
3006     VdbeCoverage(v);
3007 
3008     /* Step 7:  If we reach this point, we know that the result must
3009     ** be false. */
3010     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3011   }
3012 
3013   /* Jumps here in order to return true. */
3014   sqlite3VdbeJumpHere(v, addrTruthOp);
3015 
3016 sqlite3ExprCodeIN_finished:
3017   if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3018   sqlite3ExprCachePop(pParse);
3019   VdbeComment((v, "end IN expr"));
3020 sqlite3ExprCodeIN_oom_error:
3021   sqlite3DbFree(pParse->db, aiMap);
3022   sqlite3DbFree(pParse->db, zAff);
3023 }
3024 #endif /* SQLITE_OMIT_SUBQUERY */
3025 
3026 #ifndef SQLITE_OMIT_FLOATING_POINT
3027 /*
3028 ** Generate an instruction that will put the floating point
3029 ** value described by z[0..n-1] into register iMem.
3030 **
3031 ** The z[] string will probably not be zero-terminated.  But the
3032 ** z[n] character is guaranteed to be something that does not look
3033 ** like the continuation of the number.
3034 */
3035 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3036   if( ALWAYS(z!=0) ){
3037     double value;
3038     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3039     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3040     if( negateFlag ) value = -value;
3041     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3042   }
3043 }
3044 #endif
3045 
3046 
3047 /*
3048 ** Generate an instruction that will put the integer describe by
3049 ** text z[0..n-1] into register iMem.
3050 **
3051 ** Expr.u.zToken is always UTF8 and zero-terminated.
3052 */
3053 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3054   Vdbe *v = pParse->pVdbe;
3055   if( pExpr->flags & EP_IntValue ){
3056     int i = pExpr->u.iValue;
3057     assert( i>=0 );
3058     if( negFlag ) i = -i;
3059     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3060   }else{
3061     int c;
3062     i64 value;
3063     const char *z = pExpr->u.zToken;
3064     assert( z!=0 );
3065     c = sqlite3DecOrHexToI64(z, &value);
3066     if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
3067 #ifdef SQLITE_OMIT_FLOATING_POINT
3068       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3069 #else
3070 #ifndef SQLITE_OMIT_HEX_INTEGER
3071       if( sqlite3_strnicmp(z,"0x",2)==0 ){
3072         sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
3073       }else
3074 #endif
3075       {
3076         codeReal(v, z, negFlag, iMem);
3077       }
3078 #endif
3079     }else{
3080       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
3081       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3082     }
3083   }
3084 }
3085 
3086 /*
3087 ** Erase column-cache entry number i
3088 */
3089 static void cacheEntryClear(Parse *pParse, int i){
3090   if( pParse->aColCache[i].tempReg ){
3091     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3092       pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
3093     }
3094   }
3095   pParse->nColCache--;
3096   if( i<pParse->nColCache ){
3097     pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
3098   }
3099 }
3100 
3101 
3102 /*
3103 ** Record in the column cache that a particular column from a
3104 ** particular table is stored in a particular register.
3105 */
3106 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
3107   int i;
3108   int minLru;
3109   int idxLru;
3110   struct yColCache *p;
3111 
3112   /* Unless an error has occurred, register numbers are always positive. */
3113   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
3114   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
3115 
3116   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
3117   ** for testing only - to verify that SQLite always gets the same answer
3118   ** with and without the column cache.
3119   */
3120   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
3121 
3122   /* First replace any existing entry.
3123   **
3124   ** Actually, the way the column cache is currently used, we are guaranteed
3125   ** that the object will never already be in cache.  Verify this guarantee.
3126   */
3127 #ifndef NDEBUG
3128   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3129     assert( p->iTable!=iTab || p->iColumn!=iCol );
3130   }
3131 #endif
3132 
3133   /* If the cache is already full, delete the least recently used entry */
3134   if( pParse->nColCache>=SQLITE_N_COLCACHE ){
3135     minLru = 0x7fffffff;
3136     idxLru = -1;
3137     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3138       if( p->lru<minLru ){
3139         idxLru = i;
3140         minLru = p->lru;
3141       }
3142     }
3143     p = &pParse->aColCache[idxLru];
3144   }else{
3145     p = &pParse->aColCache[pParse->nColCache++];
3146   }
3147 
3148   /* Add the new entry to the end of the cache */
3149   p->iLevel = pParse->iCacheLevel;
3150   p->iTable = iTab;
3151   p->iColumn = iCol;
3152   p->iReg = iReg;
3153   p->tempReg = 0;
3154   p->lru = pParse->iCacheCnt++;
3155 }
3156 
3157 /*
3158 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3159 ** Purge the range of registers from the column cache.
3160 */
3161 void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
3162   int i = 0;
3163   while( i<pParse->nColCache ){
3164     struct yColCache *p = &pParse->aColCache[i];
3165     if( p->iReg >= iReg && p->iReg < iReg+nReg ){
3166       cacheEntryClear(pParse, i);
3167     }else{
3168       i++;
3169     }
3170   }
3171 }
3172 
3173 /*
3174 ** Remember the current column cache context.  Any new entries added
3175 ** added to the column cache after this call are removed when the
3176 ** corresponding pop occurs.
3177 */
3178 void sqlite3ExprCachePush(Parse *pParse){
3179   pParse->iCacheLevel++;
3180 #ifdef SQLITE_DEBUG
3181   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3182     printf("PUSH to %d\n", pParse->iCacheLevel);
3183   }
3184 #endif
3185 }
3186 
3187 /*
3188 ** Remove from the column cache any entries that were added since the
3189 ** the previous sqlite3ExprCachePush operation.  In other words, restore
3190 ** the cache to the state it was in prior the most recent Push.
3191 */
3192 void sqlite3ExprCachePop(Parse *pParse){
3193   int i = 0;
3194   assert( pParse->iCacheLevel>=1 );
3195   pParse->iCacheLevel--;
3196 #ifdef SQLITE_DEBUG
3197   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3198     printf("POP  to %d\n", pParse->iCacheLevel);
3199   }
3200 #endif
3201   while( i<pParse->nColCache ){
3202     if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
3203       cacheEntryClear(pParse, i);
3204     }else{
3205       i++;
3206     }
3207   }
3208 }
3209 
3210 /*
3211 ** When a cached column is reused, make sure that its register is
3212 ** no longer available as a temp register.  ticket #3879:  that same
3213 ** register might be in the cache in multiple places, so be sure to
3214 ** get them all.
3215 */
3216 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3217   int i;
3218   struct yColCache *p;
3219   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3220     if( p->iReg==iReg ){
3221       p->tempReg = 0;
3222     }
3223   }
3224 }
3225 
3226 /* Generate code that will load into register regOut a value that is
3227 ** appropriate for the iIdxCol-th column of index pIdx.
3228 */
3229 void sqlite3ExprCodeLoadIndexColumn(
3230   Parse *pParse,  /* The parsing context */
3231   Index *pIdx,    /* The index whose column is to be loaded */
3232   int iTabCur,    /* Cursor pointing to a table row */
3233   int iIdxCol,    /* The column of the index to be loaded */
3234   int regOut      /* Store the index column value in this register */
3235 ){
3236   i16 iTabCol = pIdx->aiColumn[iIdxCol];
3237   if( iTabCol==XN_EXPR ){
3238     assert( pIdx->aColExpr );
3239     assert( pIdx->aColExpr->nExpr>iIdxCol );
3240     pParse->iSelfTab = iTabCur;
3241     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3242   }else{
3243     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3244                                     iTabCol, regOut);
3245   }
3246 }
3247 
3248 /*
3249 ** Generate code to extract the value of the iCol-th column of a table.
3250 */
3251 void sqlite3ExprCodeGetColumnOfTable(
3252   Vdbe *v,        /* The VDBE under construction */
3253   Table *pTab,    /* The table containing the value */
3254   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
3255   int iCol,       /* Index of the column to extract */
3256   int regOut      /* Extract the value into this register */
3257 ){
3258   if( pTab==0 ){
3259     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3260     return;
3261   }
3262   if( iCol<0 || iCol==pTab->iPKey ){
3263     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3264   }else{
3265     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
3266     int x = iCol;
3267     if( !HasRowid(pTab) && !IsVirtual(pTab) ){
3268       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3269     }
3270     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3271   }
3272   if( iCol>=0 ){
3273     sqlite3ColumnDefault(v, pTab, iCol, regOut);
3274   }
3275 }
3276 
3277 /*
3278 ** Generate code that will extract the iColumn-th column from
3279 ** table pTab and store the column value in a register.
3280 **
3281 ** An effort is made to store the column value in register iReg.  This
3282 ** is not garanteeed for GetColumn() - the result can be stored in
3283 ** any register.  But the result is guaranteed to land in register iReg
3284 ** for GetColumnToReg().
3285 **
3286 ** There must be an open cursor to pTab in iTable when this routine
3287 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
3288 */
3289 int sqlite3ExprCodeGetColumn(
3290   Parse *pParse,   /* Parsing and code generating context */
3291   Table *pTab,     /* Description of the table we are reading from */
3292   int iColumn,     /* Index of the table column */
3293   int iTable,      /* The cursor pointing to the table */
3294   int iReg,        /* Store results here */
3295   u8 p5            /* P5 value for OP_Column + FLAGS */
3296 ){
3297   Vdbe *v = pParse->pVdbe;
3298   int i;
3299   struct yColCache *p;
3300 
3301   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3302     if( p->iTable==iTable && p->iColumn==iColumn ){
3303       p->lru = pParse->iCacheCnt++;
3304       sqlite3ExprCachePinRegister(pParse, p->iReg);
3305       return p->iReg;
3306     }
3307   }
3308   assert( v!=0 );
3309   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
3310   if( p5 ){
3311     sqlite3VdbeChangeP5(v, p5);
3312   }else{
3313     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3314   }
3315   return iReg;
3316 }
3317 void sqlite3ExprCodeGetColumnToReg(
3318   Parse *pParse,   /* Parsing and code generating context */
3319   Table *pTab,     /* Description of the table we are reading from */
3320   int iColumn,     /* Index of the table column */
3321   int iTable,      /* The cursor pointing to the table */
3322   int iReg         /* Store results here */
3323 ){
3324   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3325   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3326 }
3327 
3328 
3329 /*
3330 ** Clear all column cache entries.
3331 */
3332 void sqlite3ExprCacheClear(Parse *pParse){
3333   int i;
3334 
3335 #ifdef SQLITE_DEBUG
3336   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3337     printf("CLEAR\n");
3338   }
3339 #endif
3340   for(i=0; i<pParse->nColCache; i++){
3341     if( pParse->aColCache[i].tempReg
3342      && pParse->nTempReg<ArraySize(pParse->aTempReg)
3343     ){
3344        pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
3345     }
3346   }
3347   pParse->nColCache = 0;
3348 }
3349 
3350 /*
3351 ** Record the fact that an affinity change has occurred on iCount
3352 ** registers starting with iStart.
3353 */
3354 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
3355   sqlite3ExprCacheRemove(pParse, iStart, iCount);
3356 }
3357 
3358 /*
3359 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3360 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
3361 */
3362 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3363   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
3364   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3365   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
3366 }
3367 
3368 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
3369 /*
3370 ** Return true if any register in the range iFrom..iTo (inclusive)
3371 ** is used as part of the column cache.
3372 **
3373 ** This routine is used within assert() and testcase() macros only
3374 ** and does not appear in a normal build.
3375 */
3376 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3377   int i;
3378   struct yColCache *p;
3379   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3380     int r = p->iReg;
3381     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
3382   }
3383   return 0;
3384 }
3385 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
3386 
3387 
3388 /*
3389 ** Convert a scalar expression node to a TK_REGISTER referencing
3390 ** register iReg.  The caller must ensure that iReg already contains
3391 ** the correct value for the expression.
3392 */
3393 static void exprToRegister(Expr *p, int iReg){
3394   p->op2 = p->op;
3395   p->op = TK_REGISTER;
3396   p->iTable = iReg;
3397   ExprClearProperty(p, EP_Skip);
3398 }
3399 
3400 /*
3401 ** Evaluate an expression (either a vector or a scalar expression) and store
3402 ** the result in continguous temporary registers.  Return the index of
3403 ** the first register used to store the result.
3404 **
3405 ** If the returned result register is a temporary scalar, then also write
3406 ** that register number into *piFreeable.  If the returned result register
3407 ** is not a temporary or if the expression is a vector set *piFreeable
3408 ** to 0.
3409 */
3410 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3411   int iResult;
3412   int nResult = sqlite3ExprVectorSize(p);
3413   if( nResult==1 ){
3414     iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3415   }else{
3416     *piFreeable = 0;
3417     if( p->op==TK_SELECT ){
3418 #if SQLITE_OMIT_SUBQUERY
3419       iResult = 0;
3420 #else
3421       iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3422 #endif
3423     }else{
3424       int i;
3425       iResult = pParse->nMem+1;
3426       pParse->nMem += nResult;
3427       for(i=0; i<nResult; i++){
3428         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
3429       }
3430     }
3431   }
3432   return iResult;
3433 }
3434 
3435 
3436 /*
3437 ** Generate code into the current Vdbe to evaluate the given
3438 ** expression.  Attempt to store the results in register "target".
3439 ** Return the register where results are stored.
3440 **
3441 ** With this routine, there is no guarantee that results will
3442 ** be stored in target.  The result might be stored in some other
3443 ** register if it is convenient to do so.  The calling function
3444 ** must check the return code and move the results to the desired
3445 ** register.
3446 */
3447 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
3448   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
3449   int op;                   /* The opcode being coded */
3450   int inReg = target;       /* Results stored in register inReg */
3451   int regFree1 = 0;         /* If non-zero free this temporary register */
3452   int regFree2 = 0;         /* If non-zero free this temporary register */
3453   int r1, r2;               /* Various register numbers */
3454   Expr tempX;               /* Temporary expression node */
3455   int p5 = 0;
3456 
3457   assert( target>0 && target<=pParse->nMem );
3458   if( v==0 ){
3459     assert( pParse->db->mallocFailed );
3460     return 0;
3461   }
3462 
3463   if( pExpr==0 ){
3464     op = TK_NULL;
3465   }else{
3466     op = pExpr->op;
3467   }
3468   switch( op ){
3469     case TK_AGG_COLUMN: {
3470       AggInfo *pAggInfo = pExpr->pAggInfo;
3471       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3472       if( !pAggInfo->directMode ){
3473         assert( pCol->iMem>0 );
3474         return pCol->iMem;
3475       }else if( pAggInfo->useSortingIdx ){
3476         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3477                               pCol->iSorterColumn, target);
3478         return target;
3479       }
3480       /* Otherwise, fall thru into the TK_COLUMN case */
3481     }
3482     case TK_COLUMN: {
3483       int iTab = pExpr->iTable;
3484       if( iTab<0 ){
3485         if( pParse->ckBase>0 ){
3486           /* Generating CHECK constraints or inserting into partial index */
3487           return pExpr->iColumn + pParse->ckBase;
3488         }else{
3489           /* Coding an expression that is part of an index where column names
3490           ** in the index refer to the table to which the index belongs */
3491           iTab = pParse->iSelfTab;
3492         }
3493       }
3494       return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3495                                pExpr->iColumn, iTab, target,
3496                                pExpr->op2);
3497     }
3498     case TK_INTEGER: {
3499       codeInteger(pParse, pExpr, 0, target);
3500       return target;
3501     }
3502 #ifndef SQLITE_OMIT_FLOATING_POINT
3503     case TK_FLOAT: {
3504       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3505       codeReal(v, pExpr->u.zToken, 0, target);
3506       return target;
3507     }
3508 #endif
3509     case TK_STRING: {
3510       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3511       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
3512       return target;
3513     }
3514     case TK_NULL: {
3515       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3516       return target;
3517     }
3518 #ifndef SQLITE_OMIT_BLOB_LITERAL
3519     case TK_BLOB: {
3520       int n;
3521       const char *z;
3522       char *zBlob;
3523       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3524       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3525       assert( pExpr->u.zToken[1]=='\'' );
3526       z = &pExpr->u.zToken[2];
3527       n = sqlite3Strlen30(z) - 1;
3528       assert( z[n]=='\'' );
3529       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3530       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
3531       return target;
3532     }
3533 #endif
3534     case TK_VARIABLE: {
3535       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3536       assert( pExpr->u.zToken!=0 );
3537       assert( pExpr->u.zToken[0]!=0 );
3538       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3539       if( pExpr->u.zToken[1]!=0 ){
3540         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
3541         assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
3542         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
3543         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
3544       }
3545       return target;
3546     }
3547     case TK_REGISTER: {
3548       return pExpr->iTable;
3549     }
3550 #ifndef SQLITE_OMIT_CAST
3551     case TK_CAST: {
3552       /* Expressions of the form:   CAST(pLeft AS token) */
3553       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3554       if( inReg!=target ){
3555         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3556         inReg = target;
3557       }
3558       sqlite3VdbeAddOp2(v, OP_Cast, target,
3559                         sqlite3AffinityType(pExpr->u.zToken, 0));
3560       testcase( usedAsColumnCache(pParse, inReg, inReg) );
3561       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
3562       return inReg;
3563     }
3564 #endif /* SQLITE_OMIT_CAST */
3565     case TK_IS:
3566     case TK_ISNOT:
3567       op = (op==TK_IS) ? TK_EQ : TK_NE;
3568       p5 = SQLITE_NULLEQ;
3569       /* fall-through */
3570     case TK_LT:
3571     case TK_LE:
3572     case TK_GT:
3573     case TK_GE:
3574     case TK_NE:
3575     case TK_EQ: {
3576       Expr *pLeft = pExpr->pLeft;
3577       if( sqlite3ExprIsVector(pLeft) ){
3578         codeVectorCompare(pParse, pExpr, target, op, p5);
3579       }else{
3580         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3581         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3582         codeCompare(pParse, pLeft, pExpr->pRight, op,
3583             r1, r2, inReg, SQLITE_STOREP2 | p5);
3584         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3585         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3586         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3587         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3588         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3589         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3590         testcase( regFree1==0 );
3591         testcase( regFree2==0 );
3592       }
3593       break;
3594     }
3595     case TK_AND:
3596     case TK_OR:
3597     case TK_PLUS:
3598     case TK_STAR:
3599     case TK_MINUS:
3600     case TK_REM:
3601     case TK_BITAND:
3602     case TK_BITOR:
3603     case TK_SLASH:
3604     case TK_LSHIFT:
3605     case TK_RSHIFT:
3606     case TK_CONCAT: {
3607       assert( TK_AND==OP_And );            testcase( op==TK_AND );
3608       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
3609       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
3610       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
3611       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
3612       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
3613       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
3614       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
3615       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
3616       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
3617       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
3618       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3619       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3620       sqlite3VdbeAddOp3(v, op, r2, r1, target);
3621       testcase( regFree1==0 );
3622       testcase( regFree2==0 );
3623       break;
3624     }
3625     case TK_UMINUS: {
3626       Expr *pLeft = pExpr->pLeft;
3627       assert( pLeft );
3628       if( pLeft->op==TK_INTEGER ){
3629         codeInteger(pParse, pLeft, 1, target);
3630         return target;
3631 #ifndef SQLITE_OMIT_FLOATING_POINT
3632       }else if( pLeft->op==TK_FLOAT ){
3633         assert( !ExprHasProperty(pExpr, EP_IntValue) );
3634         codeReal(v, pLeft->u.zToken, 1, target);
3635         return target;
3636 #endif
3637       }else{
3638         tempX.op = TK_INTEGER;
3639         tempX.flags = EP_IntValue|EP_TokenOnly;
3640         tempX.u.iValue = 0;
3641         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
3642         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
3643         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
3644         testcase( regFree2==0 );
3645       }
3646       break;
3647     }
3648     case TK_BITNOT:
3649     case TK_NOT: {
3650       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
3651       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
3652       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3653       testcase( regFree1==0 );
3654       sqlite3VdbeAddOp2(v, op, r1, inReg);
3655       break;
3656     }
3657     case TK_ISNULL:
3658     case TK_NOTNULL: {
3659       int addr;
3660       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
3661       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
3662       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3663       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3664       testcase( regFree1==0 );
3665       addr = sqlite3VdbeAddOp1(v, op, r1);
3666       VdbeCoverageIf(v, op==TK_ISNULL);
3667       VdbeCoverageIf(v, op==TK_NOTNULL);
3668       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
3669       sqlite3VdbeJumpHere(v, addr);
3670       break;
3671     }
3672     case TK_AGG_FUNCTION: {
3673       AggInfo *pInfo = pExpr->pAggInfo;
3674       if( pInfo==0 ){
3675         assert( !ExprHasProperty(pExpr, EP_IntValue) );
3676         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
3677       }else{
3678         return pInfo->aFunc[pExpr->iAgg].iMem;
3679       }
3680       break;
3681     }
3682     case TK_FUNCTION: {
3683       ExprList *pFarg;       /* List of function arguments */
3684       int nFarg;             /* Number of function arguments */
3685       FuncDef *pDef;         /* The function definition object */
3686       const char *zId;       /* The function name */
3687       u32 constMask = 0;     /* Mask of function arguments that are constant */
3688       int i;                 /* Loop counter */
3689       sqlite3 *db = pParse->db;  /* The database connection */
3690       u8 enc = ENC(db);      /* The text encoding used by this database */
3691       CollSeq *pColl = 0;    /* A collating sequence */
3692 
3693       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
3694         /* SQL functions can be expensive. So try to move constant functions
3695         ** out of the inner loop, even if that means an extra OP_Copy. */
3696         return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
3697       }
3698       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3699       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
3700         pFarg = 0;
3701       }else{
3702         pFarg = pExpr->x.pList;
3703       }
3704       nFarg = pFarg ? pFarg->nExpr : 0;
3705       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3706       zId = pExpr->u.zToken;
3707       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
3708 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3709       if( pDef==0 && pParse->explain ){
3710         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3711       }
3712 #endif
3713       if( pDef==0 || pDef->xFinalize!=0 ){
3714         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
3715         break;
3716       }
3717 
3718       /* Attempt a direct implementation of the built-in COALESCE() and
3719       ** IFNULL() functions.  This avoids unnecessary evaluation of
3720       ** arguments past the first non-NULL argument.
3721       */
3722       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
3723         int endCoalesce = sqlite3VdbeMakeLabel(v);
3724         assert( nFarg>=2 );
3725         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3726         for(i=1; i<nFarg; i++){
3727           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3728           VdbeCoverage(v);
3729           sqlite3ExprCacheRemove(pParse, target, 1);
3730           sqlite3ExprCachePush(pParse);
3731           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3732           sqlite3ExprCachePop(pParse);
3733         }
3734         sqlite3VdbeResolveLabel(v, endCoalesce);
3735         break;
3736       }
3737 
3738       /* The UNLIKELY() function is a no-op.  The result is the value
3739       ** of the first argument.
3740       */
3741       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3742         assert( nFarg>=1 );
3743         return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3744       }
3745 
3746 #ifdef SQLITE_DEBUG
3747       /* The AFFINITY() function evaluates to a string that describes
3748       ** the type affinity of the argument.  This is used for testing of
3749       ** the SQLite type logic.
3750       */
3751       if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
3752         const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3753         char aff;
3754         assert( nFarg==1 );
3755         aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3756         sqlite3VdbeLoadString(v, target,
3757                               aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
3758         return target;
3759       }
3760 #endif
3761 
3762       for(i=0; i<nFarg; i++){
3763         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
3764           testcase( i==31 );
3765           constMask |= MASKBIT32(i);
3766         }
3767         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3768           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3769         }
3770       }
3771       if( pFarg ){
3772         if( constMask ){
3773           r1 = pParse->nMem+1;
3774           pParse->nMem += nFarg;
3775         }else{
3776           r1 = sqlite3GetTempRange(pParse, nFarg);
3777         }
3778 
3779         /* For length() and typeof() functions with a column argument,
3780         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3781         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3782         ** loading.
3783         */
3784         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
3785           u8 exprOp;
3786           assert( nFarg==1 );
3787           assert( pFarg->a[0].pExpr!=0 );
3788           exprOp = pFarg->a[0].pExpr->op;
3789           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
3790             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3791             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
3792             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3793             pFarg->a[0].pExpr->op2 =
3794                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
3795           }
3796         }
3797 
3798         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
3799         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
3800                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
3801         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
3802       }else{
3803         r1 = 0;
3804       }
3805 #ifndef SQLITE_OMIT_VIRTUALTABLE
3806       /* Possibly overload the function if the first argument is
3807       ** a virtual table column.
3808       **
3809       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3810       ** second argument, not the first, as the argument to test to
3811       ** see if it is a column in a virtual table.  This is done because
3812       ** the left operand of infix functions (the operand we want to
3813       ** control overloading) ends up as the second argument to the
3814       ** function.  The expression "A glob B" is equivalent to
3815       ** "glob(B,A).  We want to use the A in "A glob B" to test
3816       ** for function overloading.  But we use the B term in "glob(B,A)".
3817       */
3818       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3819         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3820       }else if( nFarg>0 ){
3821         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
3822       }
3823 #endif
3824       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
3825         if( !pColl ) pColl = db->pDfltColl;
3826         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3827       }
3828       sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
3829                         (char*)pDef, P4_FUNCDEF);
3830       sqlite3VdbeChangeP5(v, (u8)nFarg);
3831       if( nFarg && constMask==0 ){
3832         sqlite3ReleaseTempRange(pParse, r1, nFarg);
3833       }
3834       return target;
3835     }
3836 #ifndef SQLITE_OMIT_SUBQUERY
3837     case TK_EXISTS:
3838     case TK_SELECT: {
3839       int nCol;
3840       testcase( op==TK_EXISTS );
3841       testcase( op==TK_SELECT );
3842       if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3843         sqlite3SubselectError(pParse, nCol, 1);
3844       }else{
3845         return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3846       }
3847       break;
3848     }
3849     case TK_SELECT_COLUMN: {
3850       int n;
3851       if( pExpr->pLeft->iTable==0 ){
3852         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3853       }
3854       assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
3855       if( pExpr->iTable
3856        && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
3857       ){
3858         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
3859                                 pExpr->iTable, n);
3860       }
3861       return pExpr->pLeft->iTable + pExpr->iColumn;
3862     }
3863     case TK_IN: {
3864       int destIfFalse = sqlite3VdbeMakeLabel(v);
3865       int destIfNull = sqlite3VdbeMakeLabel(v);
3866       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3867       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3868       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3869       sqlite3VdbeResolveLabel(v, destIfFalse);
3870       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3871       sqlite3VdbeResolveLabel(v, destIfNull);
3872       return target;
3873     }
3874 #endif /* SQLITE_OMIT_SUBQUERY */
3875 
3876 
3877     /*
3878     **    x BETWEEN y AND z
3879     **
3880     ** This is equivalent to
3881     **
3882     **    x>=y AND x<=z
3883     **
3884     ** X is stored in pExpr->pLeft.
3885     ** Y is stored in pExpr->pList->a[0].pExpr.
3886     ** Z is stored in pExpr->pList->a[1].pExpr.
3887     */
3888     case TK_BETWEEN: {
3889       exprCodeBetween(pParse, pExpr, target, 0, 0);
3890       return target;
3891     }
3892     case TK_SPAN:
3893     case TK_COLLATE:
3894     case TK_UPLUS: {
3895       return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3896     }
3897 
3898     case TK_TRIGGER: {
3899       /* If the opcode is TK_TRIGGER, then the expression is a reference
3900       ** to a column in the new.* or old.* pseudo-tables available to
3901       ** trigger programs. In this case Expr.iTable is set to 1 for the
3902       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3903       ** is set to the column of the pseudo-table to read, or to -1 to
3904       ** read the rowid field.
3905       **
3906       ** The expression is implemented using an OP_Param opcode. The p1
3907       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3908       ** to reference another column of the old.* pseudo-table, where
3909       ** i is the index of the column. For a new.rowid reference, p1 is
3910       ** set to (n+1), where n is the number of columns in each pseudo-table.
3911       ** For a reference to any other column in the new.* pseudo-table, p1
3912       ** is set to (n+2+i), where n and i are as defined previously. For
3913       ** example, if the table on which triggers are being fired is
3914       ** declared as:
3915       **
3916       **   CREATE TABLE t1(a, b);
3917       **
3918       ** Then p1 is interpreted as follows:
3919       **
3920       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
3921       **   p1==1   ->    old.a         p1==4   ->    new.a
3922       **   p1==2   ->    old.b         p1==5   ->    new.b
3923       */
3924       Table *pTab = pExpr->pTab;
3925       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3926 
3927       assert( pExpr->iTable==0 || pExpr->iTable==1 );
3928       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3929       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3930       assert( p1>=0 && p1<(pTab->nCol*2+2) );
3931 
3932       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
3933       VdbeComment((v, "%s.%s -> $%d",
3934         (pExpr->iTable ? "new" : "old"),
3935         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
3936         target
3937       ));
3938 
3939 #ifndef SQLITE_OMIT_FLOATING_POINT
3940       /* If the column has REAL affinity, it may currently be stored as an
3941       ** integer. Use OP_RealAffinity to make sure it is really real.
3942       **
3943       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3944       ** floating point when extracting it from the record.  */
3945       if( pExpr->iColumn>=0
3946        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3947       ){
3948         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3949       }
3950 #endif
3951       break;
3952     }
3953 
3954     case TK_VECTOR: {
3955       sqlite3ErrorMsg(pParse, "row value misused");
3956       break;
3957     }
3958 
3959     case TK_IF_NULL_ROW: {
3960       int addrINR;
3961       addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
3962       sqlite3ExprCachePush(pParse);
3963       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3964       sqlite3ExprCachePop(pParse);
3965       sqlite3VdbeJumpHere(v, addrINR);
3966       sqlite3VdbeChangeP3(v, addrINR, inReg);
3967       break;
3968     }
3969 
3970     /*
3971     ** Form A:
3972     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3973     **
3974     ** Form B:
3975     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3976     **
3977     ** Form A is can be transformed into the equivalent form B as follows:
3978     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3979     **        WHEN x=eN THEN rN ELSE y END
3980     **
3981     ** X (if it exists) is in pExpr->pLeft.
3982     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3983     ** odd.  The Y is also optional.  If the number of elements in x.pList
3984     ** is even, then Y is omitted and the "otherwise" result is NULL.
3985     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3986     **
3987     ** The result of the expression is the Ri for the first matching Ei,
3988     ** or if there is no matching Ei, the ELSE term Y, or if there is
3989     ** no ELSE term, NULL.
3990     */
3991     default: assert( op==TK_CASE ); {
3992       int endLabel;                     /* GOTO label for end of CASE stmt */
3993       int nextCase;                     /* GOTO label for next WHEN clause */
3994       int nExpr;                        /* 2x number of WHEN terms */
3995       int i;                            /* Loop counter */
3996       ExprList *pEList;                 /* List of WHEN terms */
3997       struct ExprList_item *aListelem;  /* Array of WHEN terms */
3998       Expr opCompare;                   /* The X==Ei expression */
3999       Expr *pX;                         /* The X expression */
4000       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
4001       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
4002 
4003       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
4004       assert(pExpr->x.pList->nExpr > 0);
4005       pEList = pExpr->x.pList;
4006       aListelem = pEList->a;
4007       nExpr = pEList->nExpr;
4008       endLabel = sqlite3VdbeMakeLabel(v);
4009       if( (pX = pExpr->pLeft)!=0 ){
4010         tempX = *pX;
4011         testcase( pX->op==TK_COLUMN );
4012         exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
4013         testcase( regFree1==0 );
4014         memset(&opCompare, 0, sizeof(opCompare));
4015         opCompare.op = TK_EQ;
4016         opCompare.pLeft = &tempX;
4017         pTest = &opCompare;
4018         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4019         ** The value in regFree1 might get SCopy-ed into the file result.
4020         ** So make sure that the regFree1 register is not reused for other
4021         ** purposes and possibly overwritten.  */
4022         regFree1 = 0;
4023       }
4024       for(i=0; i<nExpr-1; i=i+2){
4025         sqlite3ExprCachePush(pParse);
4026         if( pX ){
4027           assert( pTest!=0 );
4028           opCompare.pRight = aListelem[i].pExpr;
4029         }else{
4030           pTest = aListelem[i].pExpr;
4031         }
4032         nextCase = sqlite3VdbeMakeLabel(v);
4033         testcase( pTest->op==TK_COLUMN );
4034         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4035         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4036         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4037         sqlite3VdbeGoto(v, endLabel);
4038         sqlite3ExprCachePop(pParse);
4039         sqlite3VdbeResolveLabel(v, nextCase);
4040       }
4041       if( (nExpr&1)!=0 ){
4042         sqlite3ExprCachePush(pParse);
4043         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4044         sqlite3ExprCachePop(pParse);
4045       }else{
4046         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4047       }
4048       assert( pParse->db->mallocFailed || pParse->nErr>0
4049            || pParse->iCacheLevel==iCacheLevel );
4050       sqlite3VdbeResolveLabel(v, endLabel);
4051       break;
4052     }
4053 #ifndef SQLITE_OMIT_TRIGGER
4054     case TK_RAISE: {
4055       assert( pExpr->affinity==OE_Rollback
4056            || pExpr->affinity==OE_Abort
4057            || pExpr->affinity==OE_Fail
4058            || pExpr->affinity==OE_Ignore
4059       );
4060       if( !pParse->pTriggerTab ){
4061         sqlite3ErrorMsg(pParse,
4062                        "RAISE() may only be used within a trigger-program");
4063         return 0;
4064       }
4065       if( pExpr->affinity==OE_Abort ){
4066         sqlite3MayAbort(pParse);
4067       }
4068       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4069       if( pExpr->affinity==OE_Ignore ){
4070         sqlite3VdbeAddOp4(
4071             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
4072         VdbeCoverage(v);
4073       }else{
4074         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
4075                               pExpr->affinity, pExpr->u.zToken, 0, 0);
4076       }
4077 
4078       break;
4079     }
4080 #endif
4081   }
4082   sqlite3ReleaseTempReg(pParse, regFree1);
4083   sqlite3ReleaseTempReg(pParse, regFree2);
4084   return inReg;
4085 }
4086 
4087 /*
4088 ** Factor out the code of the given expression to initialization time.
4089 **
4090 ** If regDest>=0 then the result is always stored in that register and the
4091 ** result is not reusable.  If regDest<0 then this routine is free to
4092 ** store the value whereever it wants.  The register where the expression
4093 ** is stored is returned.  When regDest<0, two identical expressions will
4094 ** code to the same register.
4095 */
4096 int sqlite3ExprCodeAtInit(
4097   Parse *pParse,    /* Parsing context */
4098   Expr *pExpr,      /* The expression to code when the VDBE initializes */
4099   int regDest       /* Store the value in this register */
4100 ){
4101   ExprList *p;
4102   assert( ConstFactorOk(pParse) );
4103   p = pParse->pConstExpr;
4104   if( regDest<0 && p ){
4105     struct ExprList_item *pItem;
4106     int i;
4107     for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
4108       if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
4109         return pItem->u.iConstExprReg;
4110       }
4111     }
4112   }
4113   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4114   p = sqlite3ExprListAppend(pParse, p, pExpr);
4115   if( p ){
4116      struct ExprList_item *pItem = &p->a[p->nExpr-1];
4117      pItem->reusable = regDest<0;
4118      if( regDest<0 ) regDest = ++pParse->nMem;
4119      pItem->u.iConstExprReg = regDest;
4120   }
4121   pParse->pConstExpr = p;
4122   return regDest;
4123 }
4124 
4125 /*
4126 ** Generate code to evaluate an expression and store the results
4127 ** into a register.  Return the register number where the results
4128 ** are stored.
4129 **
4130 ** If the register is a temporary register that can be deallocated,
4131 ** then write its number into *pReg.  If the result register is not
4132 ** a temporary, then set *pReg to zero.
4133 **
4134 ** If pExpr is a constant, then this routine might generate this
4135 ** code to fill the register in the initialization section of the
4136 ** VDBE program, in order to factor it out of the evaluation loop.
4137 */
4138 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4139   int r2;
4140   pExpr = sqlite3ExprSkipCollate(pExpr);
4141   if( ConstFactorOk(pParse)
4142    && pExpr->op!=TK_REGISTER
4143    && sqlite3ExprIsConstantNotJoin(pExpr)
4144   ){
4145     *pReg  = 0;
4146     r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
4147   }else{
4148     int r1 = sqlite3GetTempReg(pParse);
4149     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4150     if( r2==r1 ){
4151       *pReg = r1;
4152     }else{
4153       sqlite3ReleaseTempReg(pParse, r1);
4154       *pReg = 0;
4155     }
4156   }
4157   return r2;
4158 }
4159 
4160 /*
4161 ** Generate code that will evaluate expression pExpr and store the
4162 ** results in register target.  The results are guaranteed to appear
4163 ** in register target.
4164 */
4165 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
4166   int inReg;
4167 
4168   assert( target>0 && target<=pParse->nMem );
4169   if( pExpr && pExpr->op==TK_REGISTER ){
4170     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4171   }else{
4172     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
4173     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
4174     if( inReg!=target && pParse->pVdbe ){
4175       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
4176     }
4177   }
4178 }
4179 
4180 /*
4181 ** Make a transient copy of expression pExpr and then code it using
4182 ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
4183 ** except that the input expression is guaranteed to be unchanged.
4184 */
4185 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4186   sqlite3 *db = pParse->db;
4187   pExpr = sqlite3ExprDup(db, pExpr, 0);
4188   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4189   sqlite3ExprDelete(db, pExpr);
4190 }
4191 
4192 /*
4193 ** Generate code that will evaluate expression pExpr and store the
4194 ** results in register target.  The results are guaranteed to appear
4195 ** in register target.  If the expression is constant, then this routine
4196 ** might choose to code the expression at initialization time.
4197 */
4198 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4199   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4200     sqlite3ExprCodeAtInit(pParse, pExpr, target);
4201   }else{
4202     sqlite3ExprCode(pParse, pExpr, target);
4203   }
4204 }
4205 
4206 /*
4207 ** Generate code that evaluates the given expression and puts the result
4208 ** in register target.
4209 **
4210 ** Also make a copy of the expression results into another "cache" register
4211 ** and modify the expression so that the next time it is evaluated,
4212 ** the result is a copy of the cache register.
4213 **
4214 ** This routine is used for expressions that are used multiple
4215 ** times.  They are evaluated once and the results of the expression
4216 ** are reused.
4217 */
4218 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
4219   Vdbe *v = pParse->pVdbe;
4220   int iMem;
4221 
4222   assert( target>0 );
4223   assert( pExpr->op!=TK_REGISTER );
4224   sqlite3ExprCode(pParse, pExpr, target);
4225   iMem = ++pParse->nMem;
4226   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4227   exprToRegister(pExpr, iMem);
4228 }
4229 
4230 /*
4231 ** Generate code that pushes the value of every element of the given
4232 ** expression list into a sequence of registers beginning at target.
4233 **
4234 ** Return the number of elements evaluated.
4235 **
4236 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4237 ** filled using OP_SCopy.  OP_Copy must be used instead.
4238 **
4239 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4240 ** factored out into initialization code.
4241 **
4242 ** The SQLITE_ECEL_REF flag means that expressions in the list with
4243 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4244 ** in registers at srcReg, and so the value can be copied from there.
4245 */
4246 int sqlite3ExprCodeExprList(
4247   Parse *pParse,     /* Parsing context */
4248   ExprList *pList,   /* The expression list to be coded */
4249   int target,        /* Where to write results */
4250   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
4251   u8 flags           /* SQLITE_ECEL_* flags */
4252 ){
4253   struct ExprList_item *pItem;
4254   int i, j, n;
4255   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
4256   Vdbe *v = pParse->pVdbe;
4257   assert( pList!=0 );
4258   assert( target>0 );
4259   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
4260   n = pList->nExpr;
4261   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4262   for(pItem=pList->a, i=0; i<n; i++, pItem++){
4263     Expr *pExpr = pItem->pExpr;
4264     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4265       if( flags & SQLITE_ECEL_OMITREF ){
4266         i--;
4267         n--;
4268       }else{
4269         sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4270       }
4271     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
4272       sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
4273     }else{
4274       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4275       if( inReg!=target+i ){
4276         VdbeOp *pOp;
4277         if( copyOp==OP_Copy
4278          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4279          && pOp->p1+pOp->p3+1==inReg
4280          && pOp->p2+pOp->p3+1==target+i
4281         ){
4282           pOp->p3++;
4283         }else{
4284           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4285         }
4286       }
4287     }
4288   }
4289   return n;
4290 }
4291 
4292 /*
4293 ** Generate code for a BETWEEN operator.
4294 **
4295 **    x BETWEEN y AND z
4296 **
4297 ** The above is equivalent to
4298 **
4299 **    x>=y AND x<=z
4300 **
4301 ** Code it as such, taking care to do the common subexpression
4302 ** elimination of x.
4303 **
4304 ** The xJumpIf parameter determines details:
4305 **
4306 **    NULL:                   Store the boolean result in reg[dest]
4307 **    sqlite3ExprIfTrue:      Jump to dest if true
4308 **    sqlite3ExprIfFalse:     Jump to dest if false
4309 **
4310 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
4311 */
4312 static void exprCodeBetween(
4313   Parse *pParse,    /* Parsing and code generating context */
4314   Expr *pExpr,      /* The BETWEEN expression */
4315   int dest,         /* Jump destination or storage location */
4316   void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
4317   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
4318 ){
4319  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
4320   Expr compLeft;    /* The  x>=y  term */
4321   Expr compRight;   /* The  x<=z  term */
4322   Expr exprX;       /* The  x  subexpression */
4323   int regFree1 = 0; /* Temporary use register */
4324 
4325 
4326   memset(&compLeft, 0, sizeof(Expr));
4327   memset(&compRight, 0, sizeof(Expr));
4328   memset(&exprAnd, 0, sizeof(Expr));
4329 
4330   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4331   exprX = *pExpr->pLeft;
4332   exprAnd.op = TK_AND;
4333   exprAnd.pLeft = &compLeft;
4334   exprAnd.pRight = &compRight;
4335   compLeft.op = TK_GE;
4336   compLeft.pLeft = &exprX;
4337   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4338   compRight.op = TK_LE;
4339   compRight.pLeft = &exprX;
4340   compRight.pRight = pExpr->x.pList->a[1].pExpr;
4341   exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
4342   if( xJump ){
4343     xJump(pParse, &exprAnd, dest, jumpIfNull);
4344   }else{
4345     /* Mark the expression is being from the ON or USING clause of a join
4346     ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4347     ** it into the Parse.pConstExpr list.  We should use a new bit for this,
4348     ** for clarity, but we are out of bits in the Expr.flags field so we
4349     ** have to reuse the EP_FromJoin bit.  Bummer. */
4350     exprX.flags |= EP_FromJoin;
4351     sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
4352   }
4353   sqlite3ReleaseTempReg(pParse, regFree1);
4354 
4355   /* Ensure adequate test coverage */
4356   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
4357   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
4358   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
4359   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
4360   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4361   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4362   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4363   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
4364   testcase( xJump==0 );
4365 }
4366 
4367 /*
4368 ** Generate code for a boolean expression such that a jump is made
4369 ** to the label "dest" if the expression is true but execution
4370 ** continues straight thru if the expression is false.
4371 **
4372 ** If the expression evaluates to NULL (neither true nor false), then
4373 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4374 **
4375 ** This code depends on the fact that certain token values (ex: TK_EQ)
4376 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4377 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
4378 ** the make process cause these values to align.  Assert()s in the code
4379 ** below verify that the numbers are aligned correctly.
4380 */
4381 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4382   Vdbe *v = pParse->pVdbe;
4383   int op = 0;
4384   int regFree1 = 0;
4385   int regFree2 = 0;
4386   int r1, r2;
4387 
4388   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4389   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
4390   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
4391   op = pExpr->op;
4392   switch( op ){
4393     case TK_AND: {
4394       int d2 = sqlite3VdbeMakeLabel(v);
4395       testcase( jumpIfNull==0 );
4396       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
4397       sqlite3ExprCachePush(pParse);
4398       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4399       sqlite3VdbeResolveLabel(v, d2);
4400       sqlite3ExprCachePop(pParse);
4401       break;
4402     }
4403     case TK_OR: {
4404       testcase( jumpIfNull==0 );
4405       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4406       sqlite3ExprCachePush(pParse);
4407       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4408       sqlite3ExprCachePop(pParse);
4409       break;
4410     }
4411     case TK_NOT: {
4412       testcase( jumpIfNull==0 );
4413       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4414       break;
4415     }
4416     case TK_IS:
4417     case TK_ISNOT:
4418       testcase( op==TK_IS );
4419       testcase( op==TK_ISNOT );
4420       op = (op==TK_IS) ? TK_EQ : TK_NE;
4421       jumpIfNull = SQLITE_NULLEQ;
4422       /* Fall thru */
4423     case TK_LT:
4424     case TK_LE:
4425     case TK_GT:
4426     case TK_GE:
4427     case TK_NE:
4428     case TK_EQ: {
4429       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4430       testcase( jumpIfNull==0 );
4431       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4432       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4433       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4434                   r1, r2, dest, jumpIfNull);
4435       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4436       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4437       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4438       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4439       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4440       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4441       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4442       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4443       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4444       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4445       testcase( regFree1==0 );
4446       testcase( regFree2==0 );
4447       break;
4448     }
4449     case TK_ISNULL:
4450     case TK_NOTNULL: {
4451       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
4452       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4453       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4454       sqlite3VdbeAddOp2(v, op, r1, dest);
4455       VdbeCoverageIf(v, op==TK_ISNULL);
4456       VdbeCoverageIf(v, op==TK_NOTNULL);
4457       testcase( regFree1==0 );
4458       break;
4459     }
4460     case TK_BETWEEN: {
4461       testcase( jumpIfNull==0 );
4462       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
4463       break;
4464     }
4465 #ifndef SQLITE_OMIT_SUBQUERY
4466     case TK_IN: {
4467       int destIfFalse = sqlite3VdbeMakeLabel(v);
4468       int destIfNull = jumpIfNull ? dest : destIfFalse;
4469       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4470       sqlite3VdbeGoto(v, dest);
4471       sqlite3VdbeResolveLabel(v, destIfFalse);
4472       break;
4473     }
4474 #endif
4475     default: {
4476     default_expr:
4477       if( exprAlwaysTrue(pExpr) ){
4478         sqlite3VdbeGoto(v, dest);
4479       }else if( exprAlwaysFalse(pExpr) ){
4480         /* No-op */
4481       }else{
4482         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4483         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
4484         VdbeCoverage(v);
4485         testcase( regFree1==0 );
4486         testcase( jumpIfNull==0 );
4487       }
4488       break;
4489     }
4490   }
4491   sqlite3ReleaseTempReg(pParse, regFree1);
4492   sqlite3ReleaseTempReg(pParse, regFree2);
4493 }
4494 
4495 /*
4496 ** Generate code for a boolean expression such that a jump is made
4497 ** to the label "dest" if the expression is false but execution
4498 ** continues straight thru if the expression is true.
4499 **
4500 ** If the expression evaluates to NULL (neither true nor false) then
4501 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4502 ** is 0.
4503 */
4504 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4505   Vdbe *v = pParse->pVdbe;
4506   int op = 0;
4507   int regFree1 = 0;
4508   int regFree2 = 0;
4509   int r1, r2;
4510 
4511   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4512   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4513   if( pExpr==0 )    return;
4514 
4515   /* The value of pExpr->op and op are related as follows:
4516   **
4517   **       pExpr->op            op
4518   **       ---------          ----------
4519   **       TK_ISNULL          OP_NotNull
4520   **       TK_NOTNULL         OP_IsNull
4521   **       TK_NE              OP_Eq
4522   **       TK_EQ              OP_Ne
4523   **       TK_GT              OP_Le
4524   **       TK_LE              OP_Gt
4525   **       TK_GE              OP_Lt
4526   **       TK_LT              OP_Ge
4527   **
4528   ** For other values of pExpr->op, op is undefined and unused.
4529   ** The value of TK_ and OP_ constants are arranged such that we
4530   ** can compute the mapping above using the following expression.
4531   ** Assert()s verify that the computation is correct.
4532   */
4533   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4534 
4535   /* Verify correct alignment of TK_ and OP_ constants
4536   */
4537   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4538   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4539   assert( pExpr->op!=TK_NE || op==OP_Eq );
4540   assert( pExpr->op!=TK_EQ || op==OP_Ne );
4541   assert( pExpr->op!=TK_LT || op==OP_Ge );
4542   assert( pExpr->op!=TK_LE || op==OP_Gt );
4543   assert( pExpr->op!=TK_GT || op==OP_Le );
4544   assert( pExpr->op!=TK_GE || op==OP_Lt );
4545 
4546   switch( pExpr->op ){
4547     case TK_AND: {
4548       testcase( jumpIfNull==0 );
4549       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4550       sqlite3ExprCachePush(pParse);
4551       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4552       sqlite3ExprCachePop(pParse);
4553       break;
4554     }
4555     case TK_OR: {
4556       int d2 = sqlite3VdbeMakeLabel(v);
4557       testcase( jumpIfNull==0 );
4558       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
4559       sqlite3ExprCachePush(pParse);
4560       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4561       sqlite3VdbeResolveLabel(v, d2);
4562       sqlite3ExprCachePop(pParse);
4563       break;
4564     }
4565     case TK_NOT: {
4566       testcase( jumpIfNull==0 );
4567       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4568       break;
4569     }
4570     case TK_IS:
4571     case TK_ISNOT:
4572       testcase( pExpr->op==TK_IS );
4573       testcase( pExpr->op==TK_ISNOT );
4574       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4575       jumpIfNull = SQLITE_NULLEQ;
4576       /* Fall thru */
4577     case TK_LT:
4578     case TK_LE:
4579     case TK_GT:
4580     case TK_GE:
4581     case TK_NE:
4582     case TK_EQ: {
4583       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4584       testcase( jumpIfNull==0 );
4585       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4586       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4587       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4588                   r1, r2, dest, jumpIfNull);
4589       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4590       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4591       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4592       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4593       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4594       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4595       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4596       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4597       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4598       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4599       testcase( regFree1==0 );
4600       testcase( regFree2==0 );
4601       break;
4602     }
4603     case TK_ISNULL:
4604     case TK_NOTNULL: {
4605       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4606       sqlite3VdbeAddOp2(v, op, r1, dest);
4607       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
4608       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
4609       testcase( regFree1==0 );
4610       break;
4611     }
4612     case TK_BETWEEN: {
4613       testcase( jumpIfNull==0 );
4614       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
4615       break;
4616     }
4617 #ifndef SQLITE_OMIT_SUBQUERY
4618     case TK_IN: {
4619       if( jumpIfNull ){
4620         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4621       }else{
4622         int destIfNull = sqlite3VdbeMakeLabel(v);
4623         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4624         sqlite3VdbeResolveLabel(v, destIfNull);
4625       }
4626       break;
4627     }
4628 #endif
4629     default: {
4630     default_expr:
4631       if( exprAlwaysFalse(pExpr) ){
4632         sqlite3VdbeGoto(v, dest);
4633       }else if( exprAlwaysTrue(pExpr) ){
4634         /* no-op */
4635       }else{
4636         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4637         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
4638         VdbeCoverage(v);
4639         testcase( regFree1==0 );
4640         testcase( jumpIfNull==0 );
4641       }
4642       break;
4643     }
4644   }
4645   sqlite3ReleaseTempReg(pParse, regFree1);
4646   sqlite3ReleaseTempReg(pParse, regFree2);
4647 }
4648 
4649 /*
4650 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4651 ** code generation, and that copy is deleted after code generation. This
4652 ** ensures that the original pExpr is unchanged.
4653 */
4654 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4655   sqlite3 *db = pParse->db;
4656   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4657   if( db->mallocFailed==0 ){
4658     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4659   }
4660   sqlite3ExprDelete(db, pCopy);
4661 }
4662 
4663 
4664 /*
4665 ** Do a deep comparison of two expression trees.  Return 0 if the two
4666 ** expressions are completely identical.  Return 1 if they differ only
4667 ** by a COLLATE operator at the top level.  Return 2 if there are differences
4668 ** other than the top-level COLLATE operator.
4669 **
4670 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4671 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4672 **
4673 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
4674 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4675 **
4676 ** Sometimes this routine will return 2 even if the two expressions
4677 ** really are equivalent.  If we cannot prove that the expressions are
4678 ** identical, we return 2 just to be safe.  So if this routine
4679 ** returns 2, then you do not really know for certain if the two
4680 ** expressions are the same.  But if you get a 0 or 1 return, then you
4681 ** can be sure the expressions are the same.  In the places where
4682 ** this routine is used, it does not hurt to get an extra 2 - that
4683 ** just might result in some slightly slower code.  But returning
4684 ** an incorrect 0 or 1 could lead to a malfunction.
4685 */
4686 int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
4687   u32 combinedFlags;
4688   if( pA==0 || pB==0 ){
4689     return pB==pA ? 0 : 2;
4690   }
4691   combinedFlags = pA->flags | pB->flags;
4692   if( combinedFlags & EP_IntValue ){
4693     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4694       return 0;
4695     }
4696     return 2;
4697   }
4698   if( pA->op!=pB->op ){
4699     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
4700       return 1;
4701     }
4702     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
4703       return 1;
4704     }
4705     return 2;
4706   }
4707   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
4708     if( pA->op==TK_FUNCTION ){
4709       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4710     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
4711       return pA->op==TK_COLLATE ? 1 : 2;
4712     }
4713   }
4714   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
4715   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
4716     if( combinedFlags & EP_xIsSelect ) return 2;
4717     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4718     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4719     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
4720     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
4721       if( pA->iColumn!=pB->iColumn ) return 2;
4722       if( pA->iTable!=pB->iTable
4723        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
4724     }
4725   }
4726   return 0;
4727 }
4728 
4729 /*
4730 ** Compare two ExprList objects.  Return 0 if they are identical and
4731 ** non-zero if they differ in any way.
4732 **
4733 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4734 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4735 **
4736 ** This routine might return non-zero for equivalent ExprLists.  The
4737 ** only consequence will be disabled optimizations.  But this routine
4738 ** must never return 0 if the two ExprList objects are different, or
4739 ** a malfunction will result.
4740 **
4741 ** Two NULL pointers are considered to be the same.  But a NULL pointer
4742 ** always differs from a non-NULL pointer.
4743 */
4744 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
4745   int i;
4746   if( pA==0 && pB==0 ) return 0;
4747   if( pA==0 || pB==0 ) return 1;
4748   if( pA->nExpr!=pB->nExpr ) return 1;
4749   for(i=0; i<pA->nExpr; i++){
4750     Expr *pExprA = pA->a[i].pExpr;
4751     Expr *pExprB = pB->a[i].pExpr;
4752     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
4753     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
4754   }
4755   return 0;
4756 }
4757 
4758 /*
4759 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
4760 ** are ignored.
4761 */
4762 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
4763   return sqlite3ExprCompare(
4764              sqlite3ExprSkipCollate(pA),
4765              sqlite3ExprSkipCollate(pB),
4766              iTab);
4767 }
4768 
4769 /*
4770 ** Return true if we can prove the pE2 will always be true if pE1 is
4771 ** true.  Return false if we cannot complete the proof or if pE2 might
4772 ** be false.  Examples:
4773 **
4774 **     pE1: x==5       pE2: x==5             Result: true
4775 **     pE1: x>0        pE2: x==5             Result: false
4776 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
4777 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
4778 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
4779 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
4780 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
4781 **
4782 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4783 ** Expr.iTable<0 then assume a table number given by iTab.
4784 **
4785 ** When in doubt, return false.  Returning true might give a performance
4786 ** improvement.  Returning false might cause a performance reduction, but
4787 ** it will always give the correct answer and is hence always safe.
4788 */
4789 int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
4790   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4791     return 1;
4792   }
4793   if( pE2->op==TK_OR
4794    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4795              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4796   ){
4797     return 1;
4798   }
4799   if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
4800     Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
4801     testcase( pX!=pE1->pLeft );
4802     if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1;
4803   }
4804   return 0;
4805 }
4806 
4807 /*
4808 ** An instance of the following structure is used by the tree walker
4809 ** to determine if an expression can be evaluated by reference to the
4810 ** index only, without having to do a search for the corresponding
4811 ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
4812 ** is the cursor for the table.
4813 */
4814 struct IdxCover {
4815   Index *pIdx;     /* The index to be tested for coverage */
4816   int iCur;        /* Cursor number for the table corresponding to the index */
4817 };
4818 
4819 /*
4820 ** Check to see if there are references to columns in table
4821 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
4822 ** pWalker->u.pIdxCover->pIdx.
4823 */
4824 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4825   if( pExpr->op==TK_COLUMN
4826    && pExpr->iTable==pWalker->u.pIdxCover->iCur
4827    && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4828   ){
4829     pWalker->eCode = 1;
4830     return WRC_Abort;
4831   }
4832   return WRC_Continue;
4833 }
4834 
4835 /*
4836 ** Determine if an index pIdx on table with cursor iCur contains will
4837 ** the expression pExpr.  Return true if the index does cover the
4838 ** expression and false if the pExpr expression references table columns
4839 ** that are not found in the index pIdx.
4840 **
4841 ** An index covering an expression means that the expression can be
4842 ** evaluated using only the index and without having to lookup the
4843 ** corresponding table entry.
4844 */
4845 int sqlite3ExprCoveredByIndex(
4846   Expr *pExpr,        /* The index to be tested */
4847   int iCur,           /* The cursor number for the corresponding table */
4848   Index *pIdx         /* The index that might be used for coverage */
4849 ){
4850   Walker w;
4851   struct IdxCover xcov;
4852   memset(&w, 0, sizeof(w));
4853   xcov.iCur = iCur;
4854   xcov.pIdx = pIdx;
4855   w.xExprCallback = exprIdxCover;
4856   w.u.pIdxCover = &xcov;
4857   sqlite3WalkExpr(&w, pExpr);
4858   return !w.eCode;
4859 }
4860 
4861 
4862 /*
4863 ** An instance of the following structure is used by the tree walker
4864 ** to count references to table columns in the arguments of an
4865 ** aggregate function, in order to implement the
4866 ** sqlite3FunctionThisSrc() routine.
4867 */
4868 struct SrcCount {
4869   SrcList *pSrc;   /* One particular FROM clause in a nested query */
4870   int nThis;       /* Number of references to columns in pSrcList */
4871   int nOther;      /* Number of references to columns in other FROM clauses */
4872 };
4873 
4874 /*
4875 ** Count the number of references to columns.
4876 */
4877 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
4878   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4879   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4880   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
4881   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4882   ** NEVER() will need to be removed. */
4883   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
4884     int i;
4885     struct SrcCount *p = pWalker->u.pSrcCount;
4886     SrcList *pSrc = p->pSrc;
4887     int nSrc = pSrc ? pSrc->nSrc : 0;
4888     for(i=0; i<nSrc; i++){
4889       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
4890     }
4891     if( i<nSrc ){
4892       p->nThis++;
4893     }else{
4894       p->nOther++;
4895     }
4896   }
4897   return WRC_Continue;
4898 }
4899 
4900 /*
4901 ** Determine if any of the arguments to the pExpr Function reference
4902 ** pSrcList.  Return true if they do.  Also return true if the function
4903 ** has no arguments or has only constant arguments.  Return false if pExpr
4904 ** references columns but not columns of tables found in pSrcList.
4905 */
4906 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
4907   Walker w;
4908   struct SrcCount cnt;
4909   assert( pExpr->op==TK_AGG_FUNCTION );
4910   w.xExprCallback = exprSrcCount;
4911   w.xSelectCallback = 0;
4912   w.u.pSrcCount = &cnt;
4913   cnt.pSrc = pSrcList;
4914   cnt.nThis = 0;
4915   cnt.nOther = 0;
4916   sqlite3WalkExprList(&w, pExpr->x.pList);
4917   return cnt.nThis>0 || cnt.nOther==0;
4918 }
4919 
4920 /*
4921 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
4922 ** the new element.  Return a negative number if malloc fails.
4923 */
4924 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
4925   int i;
4926   pInfo->aCol = sqlite3ArrayAllocate(
4927        db,
4928        pInfo->aCol,
4929        sizeof(pInfo->aCol[0]),
4930        &pInfo->nColumn,
4931        &i
4932   );
4933   return i;
4934 }
4935 
4936 /*
4937 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
4938 ** the new element.  Return a negative number if malloc fails.
4939 */
4940 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
4941   int i;
4942   pInfo->aFunc = sqlite3ArrayAllocate(
4943        db,
4944        pInfo->aFunc,
4945        sizeof(pInfo->aFunc[0]),
4946        &pInfo->nFunc,
4947        &i
4948   );
4949   return i;
4950 }
4951 
4952 /*
4953 ** This is the xExprCallback for a tree walker.  It is used to
4954 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
4955 ** for additional information.
4956 */
4957 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
4958   int i;
4959   NameContext *pNC = pWalker->u.pNC;
4960   Parse *pParse = pNC->pParse;
4961   SrcList *pSrcList = pNC->pSrcList;
4962   AggInfo *pAggInfo = pNC->pAggInfo;
4963 
4964   switch( pExpr->op ){
4965     case TK_AGG_COLUMN:
4966     case TK_COLUMN: {
4967       testcase( pExpr->op==TK_AGG_COLUMN );
4968       testcase( pExpr->op==TK_COLUMN );
4969       /* Check to see if the column is in one of the tables in the FROM
4970       ** clause of the aggregate query */
4971       if( ALWAYS(pSrcList!=0) ){
4972         struct SrcList_item *pItem = pSrcList->a;
4973         for(i=0; i<pSrcList->nSrc; i++, pItem++){
4974           struct AggInfo_col *pCol;
4975           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4976           if( pExpr->iTable==pItem->iCursor ){
4977             /* If we reach this point, it means that pExpr refers to a table
4978             ** that is in the FROM clause of the aggregate query.
4979             **
4980             ** Make an entry for the column in pAggInfo->aCol[] if there
4981             ** is not an entry there already.
4982             */
4983             int k;
4984             pCol = pAggInfo->aCol;
4985             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
4986               if( pCol->iTable==pExpr->iTable &&
4987                   pCol->iColumn==pExpr->iColumn ){
4988                 break;
4989               }
4990             }
4991             if( (k>=pAggInfo->nColumn)
4992              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4993             ){
4994               pCol = &pAggInfo->aCol[k];
4995               pCol->pTab = pExpr->pTab;
4996               pCol->iTable = pExpr->iTable;
4997               pCol->iColumn = pExpr->iColumn;
4998               pCol->iMem = ++pParse->nMem;
4999               pCol->iSorterColumn = -1;
5000               pCol->pExpr = pExpr;
5001               if( pAggInfo->pGroupBy ){
5002                 int j, n;
5003                 ExprList *pGB = pAggInfo->pGroupBy;
5004                 struct ExprList_item *pTerm = pGB->a;
5005                 n = pGB->nExpr;
5006                 for(j=0; j<n; j++, pTerm++){
5007                   Expr *pE = pTerm->pExpr;
5008                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
5009                       pE->iColumn==pExpr->iColumn ){
5010                     pCol->iSorterColumn = j;
5011                     break;
5012                   }
5013                 }
5014               }
5015               if( pCol->iSorterColumn<0 ){
5016                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
5017               }
5018             }
5019             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
5020             ** because it was there before or because we just created it).
5021             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
5022             ** pAggInfo->aCol[] entry.
5023             */
5024             ExprSetVVAProperty(pExpr, EP_NoReduce);
5025             pExpr->pAggInfo = pAggInfo;
5026             pExpr->op = TK_AGG_COLUMN;
5027             pExpr->iAgg = (i16)k;
5028             break;
5029           } /* endif pExpr->iTable==pItem->iCursor */
5030         } /* end loop over pSrcList */
5031       }
5032       return WRC_Prune;
5033     }
5034     case TK_AGG_FUNCTION: {
5035       if( (pNC->ncFlags & NC_InAggFunc)==0
5036        && pWalker->walkerDepth==pExpr->op2
5037       ){
5038         /* Check to see if pExpr is a duplicate of another aggregate
5039         ** function that is already in the pAggInfo structure
5040         */
5041         struct AggInfo_func *pItem = pAggInfo->aFunc;
5042         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
5043           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
5044             break;
5045           }
5046         }
5047         if( i>=pAggInfo->nFunc ){
5048           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
5049           */
5050           u8 enc = ENC(pParse->db);
5051           i = addAggInfoFunc(pParse->db, pAggInfo);
5052           if( i>=0 ){
5053             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
5054             pItem = &pAggInfo->aFunc[i];
5055             pItem->pExpr = pExpr;
5056             pItem->iMem = ++pParse->nMem;
5057             assert( !ExprHasProperty(pExpr, EP_IntValue) );
5058             pItem->pFunc = sqlite3FindFunction(pParse->db,
5059                    pExpr->u.zToken,
5060                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
5061             if( pExpr->flags & EP_Distinct ){
5062               pItem->iDistinct = pParse->nTab++;
5063             }else{
5064               pItem->iDistinct = -1;
5065             }
5066           }
5067         }
5068         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
5069         */
5070         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5071         ExprSetVVAProperty(pExpr, EP_NoReduce);
5072         pExpr->iAgg = (i16)i;
5073         pExpr->pAggInfo = pAggInfo;
5074         return WRC_Prune;
5075       }else{
5076         return WRC_Continue;
5077       }
5078     }
5079   }
5080   return WRC_Continue;
5081 }
5082 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
5083   UNUSED_PARAMETER(pSelect);
5084   pWalker->walkerDepth++;
5085   return WRC_Continue;
5086 }
5087 static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
5088   UNUSED_PARAMETER(pSelect);
5089   pWalker->walkerDepth--;
5090 }
5091 
5092 /*
5093 ** Analyze the pExpr expression looking for aggregate functions and
5094 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
5095 ** points to.  Additional entries are made on the AggInfo object as
5096 ** necessary.
5097 **
5098 ** This routine should only be called after the expression has been
5099 ** analyzed by sqlite3ResolveExprNames().
5100 */
5101 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
5102   Walker w;
5103   w.xExprCallback = analyzeAggregate;
5104   w.xSelectCallback = analyzeAggregatesInSelect;
5105   w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
5106   w.walkerDepth = 0;
5107   w.u.pNC = pNC;
5108   assert( pNC->pSrcList!=0 );
5109   sqlite3WalkExpr(&w, pExpr);
5110 }
5111 
5112 /*
5113 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5114 ** expression list.  Return the number of errors.
5115 **
5116 ** If an error is found, the analysis is cut short.
5117 */
5118 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
5119   struct ExprList_item *pItem;
5120   int i;
5121   if( pList ){
5122     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5123       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
5124     }
5125   }
5126 }
5127 
5128 /*
5129 ** Allocate a single new register for use to hold some intermediate result.
5130 */
5131 int sqlite3GetTempReg(Parse *pParse){
5132   if( pParse->nTempReg==0 ){
5133     return ++pParse->nMem;
5134   }
5135   return pParse->aTempReg[--pParse->nTempReg];
5136 }
5137 
5138 /*
5139 ** Deallocate a register, making available for reuse for some other
5140 ** purpose.
5141 **
5142 ** If a register is currently being used by the column cache, then
5143 ** the deallocation is deferred until the column cache line that uses
5144 ** the register becomes stale.
5145 */
5146 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
5147   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
5148     int i;
5149     struct yColCache *p;
5150     for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
5151       if( p->iReg==iReg ){
5152         p->tempReg = 1;
5153         return;
5154       }
5155     }
5156     pParse->aTempReg[pParse->nTempReg++] = iReg;
5157   }
5158 }
5159 
5160 /*
5161 ** Allocate or deallocate a block of nReg consecutive registers.
5162 */
5163 int sqlite3GetTempRange(Parse *pParse, int nReg){
5164   int i, n;
5165   if( nReg==1 ) return sqlite3GetTempReg(pParse);
5166   i = pParse->iRangeReg;
5167   n = pParse->nRangeReg;
5168   if( nReg<=n ){
5169     assert( !usedAsColumnCache(pParse, i, i+n-1) );
5170     pParse->iRangeReg += nReg;
5171     pParse->nRangeReg -= nReg;
5172   }else{
5173     i = pParse->nMem+1;
5174     pParse->nMem += nReg;
5175   }
5176   return i;
5177 }
5178 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
5179   if( nReg==1 ){
5180     sqlite3ReleaseTempReg(pParse, iReg);
5181     return;
5182   }
5183   sqlite3ExprCacheRemove(pParse, iReg, nReg);
5184   if( nReg>pParse->nRangeReg ){
5185     pParse->nRangeReg = nReg;
5186     pParse->iRangeReg = iReg;
5187   }
5188 }
5189 
5190 /*
5191 ** Mark all temporary registers as being unavailable for reuse.
5192 */
5193 void sqlite3ClearTempRegCache(Parse *pParse){
5194   pParse->nTempReg = 0;
5195   pParse->nRangeReg = 0;
5196 }
5197 
5198 /*
5199 ** Validate that no temporary register falls within the range of
5200 ** iFirst..iLast, inclusive.  This routine is only call from within assert()
5201 ** statements.
5202 */
5203 #ifdef SQLITE_DEBUG
5204 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5205   int i;
5206   if( pParse->nRangeReg>0
5207    && pParse->iRangeReg+pParse->nRangeReg<iLast
5208    && pParse->iRangeReg>=iFirst
5209   ){
5210      return 0;
5211   }
5212   for(i=0; i<pParse->nTempReg; i++){
5213     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5214       return 0;
5215     }
5216   }
5217   return 1;
5218 }
5219 #endif /* SQLITE_DEBUG */
5220