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