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