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