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