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