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