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