LCOV - code coverage report
Current view: top level - src/backend/executor - execExpr.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 1496 1549 96.6 %
Date: 2021-12-03 03:09:03 Functions: 28 28 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * execExpr.c
       4             :  *    Expression evaluation infrastructure.
       5             :  *
       6             :  *  During executor startup, we compile each expression tree (which has
       7             :  *  previously been processed by the parser and planner) into an ExprState,
       8             :  *  using ExecInitExpr() et al.  This converts the tree into a flat array
       9             :  *  of ExprEvalSteps, which may be thought of as instructions in a program.
      10             :  *  At runtime, we'll execute steps, starting with the first, until we reach
      11             :  *  an EEOP_DONE opcode.
      12             :  *
      13             :  *  This file contains the "compilation" logic.  It is independent of the
      14             :  *  specific execution technology we use (switch statement, computed goto,
      15             :  *  JIT compilation, etc).
      16             :  *
      17             :  *  See src/backend/executor/README for some background, specifically the
      18             :  *  "Expression Trees and ExprState nodes", "Expression Initialization",
      19             :  *  and "Expression Evaluation" sections.
      20             :  *
      21             :  *
      22             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
      23             :  * Portions Copyright (c) 1994, Regents of the University of California
      24             :  *
      25             :  *
      26             :  * IDENTIFICATION
      27             :  *    src/backend/executor/execExpr.c
      28             :  *
      29             :  *-------------------------------------------------------------------------
      30             :  */
      31             : #include "postgres.h"
      32             : 
      33             : #include "access/nbtree.h"
      34             : #include "catalog/objectaccess.h"
      35             : #include "catalog/pg_type.h"
      36             : #include "executor/execExpr.h"
      37             : #include "executor/nodeSubplan.h"
      38             : #include "funcapi.h"
      39             : #include "jit/jit.h"
      40             : #include "miscadmin.h"
      41             : #include "nodes/makefuncs.h"
      42             : #include "nodes/nodeFuncs.h"
      43             : #include "nodes/subscripting.h"
      44             : #include "optimizer/optimizer.h"
      45             : #include "pgstat.h"
      46             : #include "utils/acl.h"
      47             : #include "utils/array.h"
      48             : #include "utils/builtins.h"
      49             : #include "utils/datum.h"
      50             : #include "utils/lsyscache.h"
      51             : #include "utils/typcache.h"
      52             : 
      53             : 
      54             : typedef struct LastAttnumInfo
      55             : {
      56             :     AttrNumber  last_inner;
      57             :     AttrNumber  last_outer;
      58             :     AttrNumber  last_scan;
      59             : } LastAttnumInfo;
      60             : 
      61             : static void ExecReadyExpr(ExprState *state);
      62             : static void ExecInitExprRec(Expr *node, ExprState *state,
      63             :                             Datum *resv, bool *resnull);
      64             : static void ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args,
      65             :                          Oid funcid, Oid inputcollid,
      66             :                          ExprState *state);
      67             : static void ExecInitExprSlots(ExprState *state, Node *node);
      68             : static void ExecPushExprSlots(ExprState *state, LastAttnumInfo *info);
      69             : static bool get_last_attnums_walker(Node *node, LastAttnumInfo *info);
      70             : static bool ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op);
      71             : static void ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable,
      72             :                                 ExprState *state);
      73             : static void ExecInitSubscriptingRef(ExprEvalStep *scratch,
      74             :                                     SubscriptingRef *sbsref,
      75             :                                     ExprState *state,
      76             :                                     Datum *resv, bool *resnull);
      77             : static bool isAssignmentIndirectionExpr(Expr *expr);
      78             : static void ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
      79             :                                    ExprState *state,
      80             :                                    Datum *resv, bool *resnull);
      81             : static void ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
      82             :                                   ExprEvalStep *scratch,
      83             :                                   FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
      84             :                                   int transno, int setno, int setoff, bool ishash,
      85             :                                   bool nullcheck);
      86             : 
      87             : 
      88             : /*
      89             :  * ExecInitExpr: prepare an expression tree for execution
      90             :  *
      91             :  * This function builds and returns an ExprState implementing the given
      92             :  * Expr node tree.  The return ExprState can then be handed to ExecEvalExpr
      93             :  * for execution.  Because the Expr tree itself is read-only as far as
      94             :  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
      95             :  * of the same plan tree can occur concurrently.  (But note that an ExprState
      96             :  * does mutate at runtime, so it can't be re-used concurrently.)
      97             :  *
      98             :  * This must be called in a memory context that will last as long as repeated
      99             :  * executions of the expression are needed.  Typically the context will be
     100             :  * the same as the per-query context of the associated ExprContext.
     101             :  *
     102             :  * Any Aggref, WindowFunc, or SubPlan nodes found in the tree are added to
     103             :  * the lists of such nodes held by the parent PlanState.
     104             :  *
     105             :  * Note: there is no ExecEndExpr function; we assume that any resource
     106             :  * cleanup needed will be handled by just releasing the memory context
     107             :  * in which the state tree is built.  Functions that require additional
     108             :  * cleanup work can register a shutdown callback in the ExprContext.
     109             :  *
     110             :  *  'node' is the root of the expression tree to compile.
     111             :  *  'parent' is the PlanState node that owns the expression.
     112             :  *
     113             :  * 'parent' may be NULL if we are preparing an expression that is not
     114             :  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
     115             :  * Such cases should usually come through ExecPrepareExpr, not directly here.
     116             :  *
     117             :  * Also, if 'node' is NULL, we just return NULL.  This is convenient for some
     118             :  * callers that may or may not have an expression that needs to be compiled.
     119             :  * Note that a NULL ExprState pointer *cannot* be handed to ExecEvalExpr,
     120             :  * although ExecQual and ExecCheck will accept one (and treat it as "true").
     121             :  */
     122             : ExprState *
     123     1181386 : ExecInitExpr(Expr *node, PlanState *parent)
     124             : {
     125             :     ExprState  *state;
     126     1181386 :     ExprEvalStep scratch = {0};
     127             : 
     128             :     /* Special case: NULL expression produces a NULL ExprState pointer */
     129     1181386 :     if (node == NULL)
     130      105686 :         return NULL;
     131             : 
     132             :     /* Initialize ExprState with empty step list */
     133     1075700 :     state = makeNode(ExprState);
     134     1075700 :     state->expr = node;
     135     1075700 :     state->parent = parent;
     136     1075700 :     state->ext_params = NULL;
     137             : 
     138             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     139     1075700 :     ExecInitExprSlots(state, (Node *) node);
     140             : 
     141             :     /* Compile the expression proper */
     142     1075700 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     143             : 
     144             :     /* Finally, append a DONE step */
     145     1075692 :     scratch.opcode = EEOP_DONE;
     146     1075692 :     ExprEvalPushStep(state, &scratch);
     147             : 
     148     1075692 :     ExecReadyExpr(state);
     149             : 
     150     1075692 :     return state;
     151             : }
     152             : 
     153             : /*
     154             :  * ExecInitExprWithParams: prepare a standalone expression tree for execution
     155             :  *
     156             :  * This is the same as ExecInitExpr, except that there is no parent PlanState,
     157             :  * and instead we may have a ParamListInfo describing PARAM_EXTERN Params.
     158             :  */
     159             : ExprState *
     160       50654 : ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
     161             : {
     162             :     ExprState  *state;
     163       50654 :     ExprEvalStep scratch = {0};
     164             : 
     165             :     /* Special case: NULL expression produces a NULL ExprState pointer */
     166       50654 :     if (node == NULL)
     167           0 :         return NULL;
     168             : 
     169             :     /* Initialize ExprState with empty step list */
     170       50654 :     state = makeNode(ExprState);
     171       50654 :     state->expr = node;
     172       50654 :     state->parent = NULL;
     173       50654 :     state->ext_params = ext_params;
     174             : 
     175             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     176       50654 :     ExecInitExprSlots(state, (Node *) node);
     177             : 
     178             :     /* Compile the expression proper */
     179       50654 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     180             : 
     181             :     /* Finally, append a DONE step */
     182       50654 :     scratch.opcode = EEOP_DONE;
     183       50654 :     ExprEvalPushStep(state, &scratch);
     184             : 
     185       50654 :     ExecReadyExpr(state);
     186             : 
     187       50654 :     return state;
     188             : }
     189             : 
     190             : /*
     191             :  * ExecInitQual: prepare a qual for execution by ExecQual
     192             :  *
     193             :  * Prepares for the evaluation of a conjunctive boolean expression (qual list
     194             :  * with implicit AND semantics) that returns true if none of the
     195             :  * subexpressions are false.
     196             :  *
     197             :  * We must return true if the list is empty.  Since that's a very common case,
     198             :  * we optimize it a bit further by translating to a NULL ExprState pointer
     199             :  * rather than setting up an ExprState that computes constant TRUE.  (Some
     200             :  * especially hot-spot callers of ExecQual detect this and avoid calling
     201             :  * ExecQual at all.)
     202             :  *
     203             :  * If any of the subexpressions yield NULL, then the result of the conjunction
     204             :  * is false.  This makes ExecQual primarily useful for evaluating WHERE
     205             :  * clauses, since SQL specifies that tuples with null WHERE results do not
     206             :  * get selected.
     207             :  */
     208             : ExprState *
     209     1663670 : ExecInitQual(List *qual, PlanState *parent)
     210             : {
     211             :     ExprState  *state;
     212     1663670 :     ExprEvalStep scratch = {0};
     213     1663670 :     List       *adjust_jumps = NIL;
     214             :     ListCell   *lc;
     215             : 
     216             :     /* short-circuit (here and in ExecQual) for empty restriction list */
     217     1663670 :     if (qual == NIL)
     218     1201792 :         return NULL;
     219             : 
     220             :     Assert(IsA(qual, List));
     221             : 
     222      461878 :     state = makeNode(ExprState);
     223      461878 :     state->expr = (Expr *) qual;
     224      461878 :     state->parent = parent;
     225      461878 :     state->ext_params = NULL;
     226             : 
     227             :     /* mark expression as to be used with ExecQual() */
     228      461878 :     state->flags = EEO_FLAG_IS_QUAL;
     229             : 
     230             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     231      461878 :     ExecInitExprSlots(state, (Node *) qual);
     232             : 
     233             :     /*
     234             :      * ExecQual() needs to return false for an expression returning NULL. That
     235             :      * allows us to short-circuit the evaluation the first time a NULL is
     236             :      * encountered.  As qual evaluation is a hot-path this warrants using a
     237             :      * special opcode for qual evaluation that's simpler than BOOL_AND (which
     238             :      * has more complex NULL handling).
     239             :      */
     240      461878 :     scratch.opcode = EEOP_QUAL;
     241             : 
     242             :     /*
     243             :      * We can use ExprState's resvalue/resnull as target for each qual expr.
     244             :      */
     245      461878 :     scratch.resvalue = &state->resvalue;
     246      461878 :     scratch.resnull = &state->resnull;
     247             : 
     248     1042000 :     foreach(lc, qual)
     249             :     {
     250      580122 :         Expr       *node = (Expr *) lfirst(lc);
     251             : 
     252             :         /* first evaluate expression */
     253      580122 :         ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     254             : 
     255             :         /* then emit EEOP_QUAL to detect if it's false (or null) */
     256      580122 :         scratch.d.qualexpr.jumpdone = -1;
     257      580122 :         ExprEvalPushStep(state, &scratch);
     258      580122 :         adjust_jumps = lappend_int(adjust_jumps,
     259      580122 :                                    state->steps_len - 1);
     260             :     }
     261             : 
     262             :     /* adjust jump targets */
     263     1042000 :     foreach(lc, adjust_jumps)
     264             :     {
     265      580122 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
     266             : 
     267             :         Assert(as->opcode == EEOP_QUAL);
     268             :         Assert(as->d.qualexpr.jumpdone == -1);
     269      580122 :         as->d.qualexpr.jumpdone = state->steps_len;
     270             :     }
     271             : 
     272             :     /*
     273             :      * At the end, we don't need to do anything more.  The last qual expr must
     274             :      * have yielded TRUE, and since its result is stored in the desired output
     275             :      * location, we're done.
     276             :      */
     277      461878 :     scratch.opcode = EEOP_DONE;
     278      461878 :     ExprEvalPushStep(state, &scratch);
     279             : 
     280      461878 :     ExecReadyExpr(state);
     281             : 
     282      461878 :     return state;
     283             : }
     284             : 
     285             : /*
     286             :  * ExecInitCheck: prepare a check constraint for execution by ExecCheck
     287             :  *
     288             :  * This is much like ExecInitQual/ExecQual, except that a null result from
     289             :  * the conjunction is treated as TRUE.  This behavior is appropriate for
     290             :  * evaluating CHECK constraints, since SQL specifies that NULL constraint
     291             :  * conditions are not failures.
     292             :  *
     293             :  * Note that like ExecInitQual, this expects input in implicit-AND format.
     294             :  * Users of ExecCheck that have expressions in normal explicit-AND format
     295             :  * can just apply ExecInitExpr to produce suitable input for ExecCheck.
     296             :  */
     297             : ExprState *
     298        1858 : ExecInitCheck(List *qual, PlanState *parent)
     299             : {
     300             :     /* short-circuit (here and in ExecCheck) for empty restriction list */
     301        1858 :     if (qual == NIL)
     302          24 :         return NULL;
     303             : 
     304             :     Assert(IsA(qual, List));
     305             : 
     306             :     /*
     307             :      * Just convert the implicit-AND list to an explicit AND (if there's more
     308             :      * than one entry), and compile normally.  Unlike ExecQual, we can't
     309             :      * short-circuit on NULL results, so the regular AND behavior is needed.
     310             :      */
     311        1834 :     return ExecInitExpr(make_ands_explicit(qual), parent);
     312             : }
     313             : 
     314             : /*
     315             :  * Call ExecInitExpr() on a list of expressions, return a list of ExprStates.
     316             :  */
     317             : List *
     318      749240 : ExecInitExprList(List *nodes, PlanState *parent)
     319             : {
     320      749240 :     List       *result = NIL;
     321             :     ListCell   *lc;
     322             : 
     323     1352140 :     foreach(lc, nodes)
     324             :     {
     325      602900 :         Expr       *e = lfirst(lc);
     326             : 
     327      602900 :         result = lappend(result, ExecInitExpr(e, parent));
     328             :     }
     329             : 
     330      749240 :     return result;
     331             : }
     332             : 
     333             : /*
     334             :  *      ExecBuildProjectionInfo
     335             :  *
     336             :  * Build a ProjectionInfo node for evaluating the given tlist in the given
     337             :  * econtext, and storing the result into the tuple slot.  (Caller must have
     338             :  * ensured that tuple slot has a descriptor matching the tlist!)
     339             :  *
     340             :  * inputDesc can be NULL, but if it is not, we check to see whether simple
     341             :  * Vars in the tlist match the descriptor.  It is important to provide
     342             :  * inputDesc for relation-scan plan nodes, as a cross check that the relation
     343             :  * hasn't been changed since the plan was made.  At higher levels of a plan,
     344             :  * there is no need to recheck.
     345             :  *
     346             :  * This is implemented by internally building an ExprState that performs the
     347             :  * whole projection in one go.
     348             :  *
     349             :  * Caution: before PG v10, the targetList was a list of ExprStates; now it
     350             :  * should be the planner-created targetlist, since we do the compilation here.
     351             :  */
     352             : ProjectionInfo *
     353      684534 : ExecBuildProjectionInfo(List *targetList,
     354             :                         ExprContext *econtext,
     355             :                         TupleTableSlot *slot,
     356             :                         PlanState *parent,
     357             :                         TupleDesc inputDesc)
     358             : {
     359      684534 :     ProjectionInfo *projInfo = makeNode(ProjectionInfo);
     360             :     ExprState  *state;
     361      684534 :     ExprEvalStep scratch = {0};
     362             :     ListCell   *lc;
     363             : 
     364      684534 :     projInfo->pi_exprContext = econtext;
     365             :     /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
     366      684534 :     projInfo->pi_state.type = T_ExprState;
     367      684534 :     state = &projInfo->pi_state;
     368      684534 :     state->expr = (Expr *) targetList;
     369      684534 :     state->parent = parent;
     370      684534 :     state->ext_params = NULL;
     371             : 
     372      684534 :     state->resultslot = slot;
     373             : 
     374             :     /* Insert EEOP_*_FETCHSOME steps as needed */
     375      684534 :     ExecInitExprSlots(state, (Node *) targetList);
     376             : 
     377             :     /* Now compile each tlist column */
     378     3506178 :     foreach(lc, targetList)
     379             :     {
     380     2821704 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     381     2821704 :         Var        *variable = NULL;
     382     2821704 :         AttrNumber  attnum = 0;
     383     2821704 :         bool        isSafeVar = false;
     384             : 
     385             :         /*
     386             :          * If tlist expression is a safe non-system Var, use the fast-path
     387             :          * ASSIGN_*_VAR opcodes.  "Safe" means that we don't need to apply
     388             :          * CheckVarSlotCompatibility() during plan startup.  If a source slot
     389             :          * was provided, we make the equivalent tests here; if a slot was not
     390             :          * provided, we assume that no check is needed because we're dealing
     391             :          * with a non-relation-scan-level expression.
     392             :          */
     393     2821704 :         if (tle->expr != NULL &&
     394     2821704 :             IsA(tle->expr, Var) &&
     395     1991266 :             ((Var *) tle->expr)->varattno > 0)
     396             :         {
     397             :             /* Non-system Var, but how safe is it? */
     398     1915492 :             variable = (Var *) tle->expr;
     399     1915492 :             attnum = variable->varattno;
     400             : 
     401     1915492 :             if (inputDesc == NULL)
     402     1383638 :                 isSafeVar = true;   /* can't check, just assume OK */
     403      531854 :             else if (attnum <= inputDesc->natts)
     404             :             {
     405      531678 :                 Form_pg_attribute attr = TupleDescAttr(inputDesc, attnum - 1);
     406             : 
     407             :                 /*
     408             :                  * If user attribute is dropped or has a type mismatch, don't
     409             :                  * use ASSIGN_*_VAR.  Instead let the normal expression
     410             :                  * machinery handle it (which'll possibly error out).
     411             :                  */
     412      531678 :                 if (!attr->attisdropped && variable->vartype == attr->atttypid)
     413             :                 {
     414      531492 :                     isSafeVar = true;
     415             :                 }
     416             :             }
     417             :         }
     418             : 
     419     2821704 :         if (isSafeVar)
     420             :         {
     421             :             /* Fast-path: just generate an EEOP_ASSIGN_*_VAR step */
     422     1915130 :             switch (variable->varno)
     423             :             {
     424      428480 :                 case INNER_VAR:
     425             :                     /* get the tuple from the inner node */
     426      428480 :                     scratch.opcode = EEOP_ASSIGN_INNER_VAR;
     427      428480 :                     break;
     428             : 
     429      954400 :                 case OUTER_VAR:
     430             :                     /* get the tuple from the outer node */
     431      954400 :                     scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
     432      954400 :                     break;
     433             : 
     434             :                     /* INDEX_VAR is handled by default case */
     435             : 
     436      532250 :                 default:
     437             :                     /* get the tuple from the relation being scanned */
     438      532250 :                     scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
     439      532250 :                     break;
     440             :             }
     441             : 
     442     1915130 :             scratch.d.assign_var.attnum = attnum - 1;
     443     1915130 :             scratch.d.assign_var.resultnum = tle->resno - 1;
     444     1915130 :             ExprEvalPushStep(state, &scratch);
     445             :         }
     446             :         else
     447             :         {
     448             :             /*
     449             :              * Otherwise, compile the column expression normally.
     450             :              *
     451             :              * We can't tell the expression to evaluate directly into the
     452             :              * result slot, as the result slot (and the exprstate for that
     453             :              * matter) can change between executions.  We instead evaluate
     454             :              * into the ExprState's resvalue/resnull and then move.
     455             :              */
     456      906574 :             ExecInitExprRec(tle->expr, state,
     457             :                             &state->resvalue, &state->resnull);
     458             : 
     459             :             /*
     460             :              * Column might be referenced multiple times in upper nodes, so
     461             :              * force value to R/O - but only if it could be an expanded datum.
     462             :              */
     463      906514 :             if (get_typlen(exprType((Node *) tle->expr)) == -1)
     464      428298 :                 scratch.opcode = EEOP_ASSIGN_TMP_MAKE_RO;
     465             :             else
     466      478216 :                 scratch.opcode = EEOP_ASSIGN_TMP;
     467      906514 :             scratch.d.assign_tmp.resultnum = tle->resno - 1;
     468      906514 :             ExprEvalPushStep(state, &scratch);
     469             :         }
     470             :     }
     471             : 
     472      684474 :     scratch.opcode = EEOP_DONE;
     473      684474 :     ExprEvalPushStep(state, &scratch);
     474             : 
     475      684474 :     ExecReadyExpr(state);
     476             : 
     477      684474 :     return projInfo;
     478             : }
     479             : 
     480             : /*
     481             :  *      ExecBuildUpdateProjection
     482             :  *
     483             :  * Build a ProjectionInfo node for constructing a new tuple during UPDATE.
     484             :  * The projection will be executed in the given econtext and the result will
     485             :  * be stored into the given tuple slot.  (Caller must have ensured that tuple
     486             :  * slot has a descriptor matching the target rel!)
     487             :  *
     488             :  * When evalTargetList is false, targetList contains the UPDATE ... SET
     489             :  * expressions that have already been computed by a subplan node; the values
     490             :  * from this tlist are assumed to be available in the "outer" tuple slot.
     491             :  * When evalTargetList is true, targetList contains the UPDATE ... SET
     492             :  * expressions that must be computed (which could contain references to
     493             :  * the outer, inner, or scan tuple slots).
     494             :  *
     495             :  * In either case, targetColnos contains a list of the target column numbers
     496             :  * corresponding to the non-resjunk entries of targetList.  The tlist values
     497             :  * are assigned into these columns of the result tuple slot.  Target columns
     498             :  * not listed in targetColnos are filled from the UPDATE's old tuple, which
     499             :  * is assumed to be available in the "scan" tuple slot.
     500             :  *
     501             :  * targetList can also contain resjunk columns.  These must be evaluated
     502             :  * if evalTargetList is true, but their values are discarded.
     503             :  *
     504             :  * relDesc must describe the relation we intend to update.
     505             :  *
     506             :  * This is basically a specialized variant of ExecBuildProjectionInfo.
     507             :  * However, it also performs sanity checks equivalent to ExecCheckPlanOutput.
     508             :  * Since we never make a normal tlist equivalent to the whole
     509             :  * tuple-to-be-assigned, there is no convenient way to apply
     510             :  * ExecCheckPlanOutput, so we must do our safety checks here.
     511             :  */
     512             : ProjectionInfo *
     513       11660 : ExecBuildUpdateProjection(List *targetList,
     514             :                           bool evalTargetList,
     515             :                           List *targetColnos,
     516             :                           TupleDesc relDesc,
     517             :                           ExprContext *econtext,
     518             :                           TupleTableSlot *slot,
     519             :                           PlanState *parent)
     520             : {
     521       11660 :     ProjectionInfo *projInfo = makeNode(ProjectionInfo);
     522             :     ExprState  *state;
     523             :     int         nAssignableCols;
     524             :     bool        sawJunk;
     525             :     Bitmapset  *assignedCols;
     526       11660 :     LastAttnumInfo deform = {0, 0, 0};
     527       11660 :     ExprEvalStep scratch = {0};
     528             :     int         outerattnum;
     529             :     ListCell   *lc,
     530             :                *lc2;
     531             : 
     532       11660 :     projInfo->pi_exprContext = econtext;
     533             :     /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
     534       11660 :     projInfo->pi_state.type = T_ExprState;
     535       11660 :     state = &projInfo->pi_state;
     536       11660 :     if (evalTargetList)
     537         664 :         state->expr = (Expr *) targetList;
     538             :     else
     539       10996 :         state->expr = NULL;      /* not used */
     540       11660 :     state->parent = parent;
     541       11660 :     state->ext_params = NULL;
     542             : 
     543       11660 :     state->resultslot = slot;
     544             : 
     545             :     /*
     546             :      * Examine the targetList to see how many non-junk columns there are, and
     547             :      * to verify that the non-junk columns come before the junk ones.
     548             :      */
     549       11660 :     nAssignableCols = 0;
     550       11660 :     sawJunk = false;
     551       39764 :     foreach(lc, targetList)
     552             :     {
     553       28104 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     554             : 
     555       28104 :         if (tle->resjunk)
     556       13098 :             sawJunk = true;
     557             :         else
     558             :         {
     559       15006 :             if (sawJunk)
     560           0 :                 elog(ERROR, "subplan target list is out of order");
     561       15006 :             nAssignableCols++;
     562             :         }
     563             :     }
     564             : 
     565             :     /* We should have one targetColnos entry per non-junk column */
     566       11660 :     if (nAssignableCols != list_length(targetColnos))
     567           0 :         elog(ERROR, "targetColnos does not match subplan target list");
     568             : 
     569             :     /*
     570             :      * Build a bitmapset of the columns in targetColnos.  (We could just use
     571             :      * list_member_int() tests, but that risks O(N^2) behavior with many
     572             :      * columns.)
     573             :      */
     574       11660 :     assignedCols = NULL;
     575       26666 :     foreach(lc, targetColnos)
     576             :     {
     577       15006 :         AttrNumber  targetattnum = lfirst_int(lc);
     578             : 
     579       15006 :         assignedCols = bms_add_member(assignedCols, targetattnum);
     580             :     }
     581             : 
     582             :     /*
     583             :      * We need to insert EEOP_*_FETCHSOME steps to ensure the input tuples are
     584             :      * sufficiently deconstructed.  The scan tuple must be deconstructed at
     585             :      * least as far as the last old column we need.
     586             :      */
     587       18102 :     for (int attnum = relDesc->natts; attnum > 0; attnum--)
     588             :     {
     589       16706 :         Form_pg_attribute attr = TupleDescAttr(relDesc, attnum - 1);
     590             : 
     591       16706 :         if (attr->attisdropped)
     592         122 :             continue;
     593       16584 :         if (bms_is_member(attnum, assignedCols))
     594        6320 :             continue;
     595       10264 :         deform.last_scan = attnum;
     596       10264 :         break;
     597             :     }
     598             : 
     599             :     /*
     600             :      * If we're actually evaluating the tlist, incorporate its input
     601             :      * requirements too; otherwise, we'll just need to fetch the appropriate
     602             :      * number of columns of the "outer" tuple.
     603             :      */
     604       11660 :     if (evalTargetList)
     605         664 :         get_last_attnums_walker((Node *) targetList, &deform);
     606             :     else
     607       10996 :         deform.last_outer = nAssignableCols;
     608             : 
     609       11660 :     ExecPushExprSlots(state, &deform);
     610             : 
     611             :     /*
     612             :      * Now generate code to evaluate the tlist's assignable expressions or
     613             :      * fetch them from the outer tuple, incidentally validating that they'll
     614             :      * be of the right data type.  The checks above ensure that the forboth()
     615             :      * will iterate over exactly the non-junk columns.
     616             :      */
     617       11660 :     outerattnum = 0;
     618       26666 :     forboth(lc, targetList, lc2, targetColnos)
     619             :     {
     620       15006 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     621       15006 :         AttrNumber  targetattnum = lfirst_int(lc2);
     622             :         Form_pg_attribute attr;
     623             : 
     624             :         Assert(!tle->resjunk);
     625             : 
     626             :         /*
     627             :          * Apply sanity checks comparable to ExecCheckPlanOutput().
     628             :          */
     629       15006 :         if (targetattnum <= 0 || targetattnum > relDesc->natts)
     630           0 :             ereport(ERROR,
     631             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     632             :                      errmsg("table row type and query-specified row type do not match"),
     633             :                      errdetail("Query has too many columns.")));
     634       15006 :         attr = TupleDescAttr(relDesc, targetattnum - 1);
     635             : 
     636       15006 :         if (attr->attisdropped)
     637           0 :             ereport(ERROR,
     638             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     639             :                      errmsg("table row type and query-specified row type do not match"),
     640             :                      errdetail("Query provides a value for a dropped column at ordinal position %d.",
     641             :                                targetattnum)));
     642       15006 :         if (exprType((Node *) tle->expr) != attr->atttypid)
     643           0 :             ereport(ERROR,
     644             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     645             :                      errmsg("table row type and query-specified row type do not match"),
     646             :                      errdetail("Table has type %s at ordinal position %d, but query expects %s.",
     647             :                                format_type_be(attr->atttypid),
     648             :                                targetattnum,
     649             :                                format_type_be(exprType((Node *) tle->expr)))));
     650             : 
     651             :         /* OK, generate code to perform the assignment. */
     652       15006 :         if (evalTargetList)
     653             :         {
     654             :             /*
     655             :              * We must evaluate the TLE's expression and assign it.  We do not
     656             :              * bother jumping through hoops for "safe" Vars like
     657             :              * ExecBuildProjectionInfo does; this is a relatively less-used
     658             :              * path and it doesn't seem worth expending code for that.
     659             :              */
     660         824 :             ExecInitExprRec(tle->expr, state,
     661             :                             &state->resvalue, &state->resnull);
     662             :             /* Needn't worry about read-only-ness here, either. */
     663         824 :             scratch.opcode = EEOP_ASSIGN_TMP;
     664         824 :             scratch.d.assign_tmp.resultnum = targetattnum - 1;
     665         824 :             ExprEvalPushStep(state, &scratch);
     666             :         }
     667             :         else
     668             :         {
     669             :             /* Just assign from the outer tuple. */
     670       14182 :             scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
     671       14182 :             scratch.d.assign_var.attnum = outerattnum;
     672       14182 :             scratch.d.assign_var.resultnum = targetattnum - 1;
     673       14182 :             ExprEvalPushStep(state, &scratch);
     674             :         }
     675       15006 :         outerattnum++;
     676             :     }
     677             : 
     678             :     /*
     679             :      * If we're evaluating the tlist, must evaluate any resjunk columns too.
     680             :      * (This matters for things like MULTIEXPR_SUBLINK SubPlans.)
     681             :      */
     682       11660 :     if (evalTargetList)
     683             :     {
     684         704 :         for_each_cell(lc, targetList, lc)
     685             :         {
     686          40 :             TargetEntry *tle = lfirst_node(TargetEntry, lc);
     687             : 
     688             :             Assert(tle->resjunk);
     689          40 :             ExecInitExprRec(tle->expr, state,
     690             :                             &state->resvalue, &state->resnull);
     691             :         }
     692             :     }
     693             : 
     694             :     /*
     695             :      * Now generate code to copy over any old columns that were not assigned
     696             :      * to, and to ensure that dropped columns are set to NULL.
     697             :      */
     698      141272 :     for (int attnum = 1; attnum <= relDesc->natts; attnum++)
     699             :     {
     700      129612 :         Form_pg_attribute attr = TupleDescAttr(relDesc, attnum - 1);
     701             : 
     702      129612 :         if (attr->attisdropped)
     703             :         {
     704             :             /* Put a null into the ExprState's resvalue/resnull ... */
     705         184 :             scratch.opcode = EEOP_CONST;
     706         184 :             scratch.resvalue = &state->resvalue;
     707         184 :             scratch.resnull = &state->resnull;
     708         184 :             scratch.d.constval.value = (Datum) 0;
     709         184 :             scratch.d.constval.isnull = true;
     710         184 :             ExprEvalPushStep(state, &scratch);
     711             :             /* ... then assign it to the result slot */
     712         184 :             scratch.opcode = EEOP_ASSIGN_TMP;
     713         184 :             scratch.d.assign_tmp.resultnum = attnum - 1;
     714         184 :             ExprEvalPushStep(state, &scratch);
     715             :         }
     716      129428 :         else if (!bms_is_member(attnum, assignedCols))
     717             :         {
     718             :             /* Certainly the right type, so needn't check */
     719      114422 :             scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
     720      114422 :             scratch.d.assign_var.attnum = attnum - 1;
     721      114422 :             scratch.d.assign_var.resultnum = attnum - 1;
     722      114422 :             ExprEvalPushStep(state, &scratch);
     723             :         }
     724             :     }
     725             : 
     726       11660 :     scratch.opcode = EEOP_DONE;
     727       11660 :     ExprEvalPushStep(state, &scratch);
     728             : 
     729       11660 :     ExecReadyExpr(state);
     730             : 
     731       11660 :     return projInfo;
     732             : }
     733             : 
     734             : /*
     735             :  * ExecPrepareExpr --- initialize for expression execution outside a normal
     736             :  * Plan tree context.
     737             :  *
     738             :  * This differs from ExecInitExpr in that we don't assume the caller is
     739             :  * already running in the EState's per-query context.  Also, we run the
     740             :  * passed expression tree through expression_planner() to prepare it for
     741             :  * execution.  (In ordinary Plan trees the regular planning process will have
     742             :  * made the appropriate transformations on expressions, but for standalone
     743             :  * expressions this won't have happened.)
     744             :  */
     745             : ExprState *
     746        5862 : ExecPrepareExpr(Expr *node, EState *estate)
     747             : {
     748             :     ExprState  *result;
     749             :     MemoryContext oldcontext;
     750             : 
     751        5862 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     752             : 
     753        5862 :     node = expression_planner(node);
     754             : 
     755        5862 :     result = ExecInitExpr(node, NULL);
     756             : 
     757        5862 :     MemoryContextSwitchTo(oldcontext);
     758             : 
     759        5862 :     return result;
     760             : }
     761             : 
     762             : /*
     763             :  * ExecPrepareQual --- initialize for qual execution outside a normal
     764             :  * Plan tree context.
     765             :  *
     766             :  * This differs from ExecInitQual in that we don't assume the caller is
     767             :  * already running in the EState's per-query context.  Also, we run the
     768             :  * passed expression tree through expression_planner() to prepare it for
     769             :  * execution.  (In ordinary Plan trees the regular planning process will have
     770             :  * made the appropriate transformations on expressions, but for standalone
     771             :  * expressions this won't have happened.)
     772             :  */
     773             : ExprState *
     774      101354 : ExecPrepareQual(List *qual, EState *estate)
     775             : {
     776             :     ExprState  *result;
     777             :     MemoryContext oldcontext;
     778             : 
     779      101354 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     780             : 
     781      101354 :     qual = (List *) expression_planner((Expr *) qual);
     782             : 
     783      101354 :     result = ExecInitQual(qual, NULL);
     784             : 
     785      101354 :     MemoryContextSwitchTo(oldcontext);
     786             : 
     787      101354 :     return result;
     788             : }
     789             : 
     790             : /*
     791             :  * ExecPrepareCheck -- initialize check constraint for execution outside a
     792             :  * normal Plan tree context.
     793             :  *
     794             :  * See ExecPrepareExpr() and ExecInitCheck() for details.
     795             :  */
     796             : ExprState *
     797        1858 : ExecPrepareCheck(List *qual, EState *estate)
     798             : {
     799             :     ExprState  *result;
     800             :     MemoryContext oldcontext;
     801             : 
     802        1858 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     803             : 
     804        1858 :     qual = (List *) expression_planner((Expr *) qual);
     805             : 
     806        1858 :     result = ExecInitCheck(qual, NULL);
     807             : 
     808        1858 :     MemoryContextSwitchTo(oldcontext);
     809             : 
     810        1858 :     return result;
     811             : }
     812             : 
     813             : /*
     814             :  * Call ExecPrepareExpr() on each member of a list of Exprs, and return
     815             :  * a list of ExprStates.
     816             :  *
     817             :  * See ExecPrepareExpr() for details.
     818             :  */
     819             : List *
     820        1368 : ExecPrepareExprList(List *nodes, EState *estate)
     821             : {
     822        1368 :     List       *result = NIL;
     823             :     MemoryContext oldcontext;
     824             :     ListCell   *lc;
     825             : 
     826             :     /* Ensure that the list cell nodes are in the right context too */
     827        1368 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     828             : 
     829        2952 :     foreach(lc, nodes)
     830             :     {
     831        1584 :         Expr       *e = (Expr *) lfirst(lc);
     832             : 
     833        1584 :         result = lappend(result, ExecPrepareExpr(e, estate));
     834             :     }
     835             : 
     836        1368 :     MemoryContextSwitchTo(oldcontext);
     837             : 
     838        1368 :     return result;
     839             : }
     840             : 
     841             : /*
     842             :  * ExecCheck - evaluate a check constraint
     843             :  *
     844             :  * For check constraints, a null result is taken as TRUE, ie the constraint
     845             :  * passes.
     846             :  *
     847             :  * The check constraint may have been prepared with ExecInitCheck
     848             :  * (possibly via ExecPrepareCheck) if the caller had it in implicit-AND
     849             :  * format, but a regular boolean expression prepared with ExecInitExpr or
     850             :  * ExecPrepareExpr works too.
     851             :  */
     852             : bool
     853      366010 : ExecCheck(ExprState *state, ExprContext *econtext)
     854             : {
     855             :     Datum       ret;
     856             :     bool        isnull;
     857             : 
     858             :     /* short-circuit (here and in ExecInitCheck) for empty restriction list */
     859      366010 :     if (state == NULL)
     860          24 :         return true;
     861             : 
     862             :     /* verify that expression was not compiled using ExecInitQual */
     863             :     Assert(!(state->flags & EEO_FLAG_IS_QUAL));
     864             : 
     865      365986 :     ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
     866             : 
     867      365986 :     if (isnull)
     868        1868 :         return true;
     869             : 
     870      364118 :     return DatumGetBool(ret);
     871             : }
     872             : 
     873             : /*
     874             :  * Prepare a compiled expression for execution.  This has to be called for
     875             :  * every ExprState before it can be executed.
     876             :  *
     877             :  * NB: While this currently only calls ExecReadyInterpretedExpr(),
     878             :  * this will likely get extended to further expression evaluation methods.
     879             :  * Therefore this should be used instead of directly calling
     880             :  * ExecReadyInterpretedExpr().
     881             :  */
     882             : static void
     883     2354732 : ExecReadyExpr(ExprState *state)
     884             : {
     885     2354732 :     if (jit_compile_expr(state))
     886        6032 :         return;
     887             : 
     888     2348700 :     ExecReadyInterpretedExpr(state);
     889             : }
     890             : 
     891             : /*
     892             :  * Append the steps necessary for the evaluation of node to ExprState->steps,
     893             :  * possibly recursing into sub-expressions of node.
     894             :  *
     895             :  * node - expression to evaluate
     896             :  * state - ExprState to whose ->steps to append the necessary operations
     897             :  * resv / resnull - where to store the result of the node into
     898             :  */
     899             : static void
     900     4950720 : ExecInitExprRec(Expr *node, ExprState *state,
     901             :                 Datum *resv, bool *resnull)
     902             : {
     903     4950720 :     ExprEvalStep scratch = {0};
     904             : 
     905             :     /* Guard against stack overflow due to overly complex expressions */
     906     4950720 :     check_stack_depth();
     907             : 
     908             :     /* Step's output location is always what the caller gave us */
     909             :     Assert(resv != NULL && resnull != NULL);
     910     4950720 :     scratch.resvalue = resv;
     911     4950720 :     scratch.resnull = resnull;
     912             : 
     913             :     /* cases should be ordered as they are in enum NodeTag */
     914     4950720 :     switch (nodeTag(node))
     915             :     {
     916     1531362 :         case T_Var:
     917             :             {
     918     1531362 :                 Var        *variable = (Var *) node;
     919             : 
     920     1531362 :                 if (variable->varattno == InvalidAttrNumber)
     921             :                 {
     922             :                     /* whole-row Var */
     923        2470 :                     ExecInitWholeRowVar(&scratch, variable, state);
     924             :                 }
     925     1528892 :                 else if (variable->varattno <= 0)
     926             :                 {
     927             :                     /* system column */
     928       75730 :                     scratch.d.var.attnum = variable->varattno;
     929       75730 :                     scratch.d.var.vartype = variable->vartype;
     930       75730 :                     switch (variable->varno)
     931             :                     {
     932           4 :                         case INNER_VAR:
     933           4 :                             scratch.opcode = EEOP_INNER_SYSVAR;
     934           4 :                             break;
     935           8 :                         case OUTER_VAR:
     936           8 :                             scratch.opcode = EEOP_OUTER_SYSVAR;
     937           8 :                             break;
     938             : 
     939             :                             /* INDEX_VAR is handled by default case */
     940             : 
     941       75718 :                         default:
     942       75718 :                             scratch.opcode = EEOP_SCAN_SYSVAR;
     943       75718 :                             break;
     944             :                     }
     945             :                 }
     946             :                 else
     947             :                 {
     948             :                     /* regular user column */
     949     1453162 :                     scratch.d.var.attnum = variable->varattno - 1;
     950     1453162 :                     scratch.d.var.vartype = variable->vartype;
     951     1453162 :                     switch (variable->varno)
     952             :                     {
     953      221714 :                         case INNER_VAR:
     954      221714 :                             scratch.opcode = EEOP_INNER_VAR;
     955      221714 :                             break;
     956      610448 :                         case OUTER_VAR:
     957      610448 :                             scratch.opcode = EEOP_OUTER_VAR;
     958      610448 :                             break;
     959             : 
     960             :                             /* INDEX_VAR is handled by default case */
     961             : 
     962      621000 :                         default:
     963      621000 :                             scratch.opcode = EEOP_SCAN_VAR;
     964      621000 :                             break;
     965             :                     }
     966             :                 }
     967             : 
     968     1531362 :                 ExprEvalPushStep(state, &scratch);
     969     1531362 :                 break;
     970             :             }
     971             : 
     972      893216 :         case T_Const:
     973             :             {
     974      893216 :                 Const      *con = (Const *) node;
     975             : 
     976      893216 :                 scratch.opcode = EEOP_CONST;
     977      893216 :                 scratch.d.constval.value = con->constvalue;
     978      893216 :                 scratch.d.constval.isnull = con->constisnull;
     979             : 
     980      893216 :                 ExprEvalPushStep(state, &scratch);
     981      893216 :                 break;
     982             :             }
     983             : 
     984      495246 :         case T_Param:
     985             :             {
     986      495246 :                 Param      *param = (Param *) node;
     987             :                 ParamListInfo params;
     988             : 
     989      495246 :                 switch (param->paramkind)
     990             :                 {
     991      292100 :                     case PARAM_EXEC:
     992      292100 :                         scratch.opcode = EEOP_PARAM_EXEC;
     993      292100 :                         scratch.d.param.paramid = param->paramid;
     994      292100 :                         scratch.d.param.paramtype = param->paramtype;
     995      292100 :                         ExprEvalPushStep(state, &scratch);
     996      292100 :                         break;
     997      203146 :                     case PARAM_EXTERN:
     998             : 
     999             :                         /*
    1000             :                          * If we have a relevant ParamCompileHook, use it;
    1001             :                          * otherwise compile a standard EEOP_PARAM_EXTERN
    1002             :                          * step.  ext_params, if supplied, takes precedence
    1003             :                          * over info from the parent node's EState (if any).
    1004             :                          */
    1005      203146 :                         if (state->ext_params)
    1006       45304 :                             params = state->ext_params;
    1007      157842 :                         else if (state->parent &&
    1008      157590 :                                  state->parent->state)
    1009      157590 :                             params = state->parent->state->es_param_list_info;
    1010             :                         else
    1011         252 :                             params = NULL;
    1012      203146 :                         if (params && params->paramCompile)
    1013             :                         {
    1014       76628 :                             params->paramCompile(params, param, state,
    1015             :                                                  resv, resnull);
    1016             :                         }
    1017             :                         else
    1018             :                         {
    1019      126518 :                             scratch.opcode = EEOP_PARAM_EXTERN;
    1020      126518 :                             scratch.d.param.paramid = param->paramid;
    1021      126518 :                             scratch.d.param.paramtype = param->paramtype;
    1022      126518 :                             ExprEvalPushStep(state, &scratch);
    1023             :                         }
    1024      203146 :                         break;
    1025           0 :                     default:
    1026           0 :                         elog(ERROR, "unrecognized paramkind: %d",
    1027             :                              (int) param->paramkind);
    1028             :                         break;
    1029             :                 }
    1030      495246 :                 break;
    1031             :             }
    1032             : 
    1033       59484 :         case T_Aggref:
    1034             :             {
    1035       59484 :                 Aggref     *aggref = (Aggref *) node;
    1036             : 
    1037       59484 :                 scratch.opcode = EEOP_AGGREF;
    1038       59484 :                 scratch.d.aggref.aggno = aggref->aggno;
    1039             : 
    1040       59484 :                 if (state->parent && IsA(state->parent, AggState))
    1041       59484 :                 {
    1042       59484 :                     AggState   *aggstate = (AggState *) state->parent;
    1043             : 
    1044       59484 :                     aggstate->aggs = lappend(aggstate->aggs, aggref);
    1045             :                 }
    1046             :                 else
    1047             :                 {
    1048             :                     /* planner messed up */
    1049           0 :                     elog(ERROR, "Aggref found in non-Agg plan node");
    1050             :                 }
    1051             : 
    1052       59484 :                 ExprEvalPushStep(state, &scratch);
    1053       59484 :                 break;
    1054             :             }
    1055             : 
    1056         172 :         case T_GroupingFunc:
    1057             :             {
    1058         172 :                 GroupingFunc *grp_node = (GroupingFunc *) node;
    1059             :                 Agg        *agg;
    1060             : 
    1061         172 :                 if (!state->parent || !IsA(state->parent, AggState) ||
    1062         172 :                     !IsA(state->parent->plan, Agg))
    1063           0 :                     elog(ERROR, "GroupingFunc found in non-Agg plan node");
    1064             : 
    1065         172 :                 scratch.opcode = EEOP_GROUPING_FUNC;
    1066             : 
    1067         172 :                 agg = (Agg *) (state->parent->plan);
    1068             : 
    1069         172 :                 if (agg->groupingSets)
    1070         134 :                     scratch.d.grouping_func.clauses = grp_node->cols;
    1071             :                 else
    1072          38 :                     scratch.d.grouping_func.clauses = NIL;
    1073             : 
    1074         172 :                 ExprEvalPushStep(state, &scratch);
    1075         172 :                 break;
    1076             :             }
    1077             : 
    1078        1512 :         case T_WindowFunc:
    1079             :             {
    1080        1512 :                 WindowFunc *wfunc = (WindowFunc *) node;
    1081        1512 :                 WindowFuncExprState *wfstate = makeNode(WindowFuncExprState);
    1082             : 
    1083        1512 :                 wfstate->wfunc = wfunc;
    1084             : 
    1085        1512 :                 if (state->parent && IsA(state->parent, WindowAggState))
    1086        1512 :                 {
    1087        1512 :                     WindowAggState *winstate = (WindowAggState *) state->parent;
    1088             :                     int         nfuncs;
    1089             : 
    1090        1512 :                     winstate->funcs = lappend(winstate->funcs, wfstate);
    1091        1512 :                     nfuncs = ++winstate->numfuncs;
    1092        1512 :                     if (wfunc->winagg)
    1093         768 :                         winstate->numaggs++;
    1094             : 
    1095             :                     /* for now initialize agg using old style expressions */
    1096        3024 :                     wfstate->args = ExecInitExprList(wfunc->args,
    1097        1512 :                                                      state->parent);
    1098        3024 :                     wfstate->aggfilter = ExecInitExpr(wfunc->aggfilter,
    1099        1512 :                                                       state->parent);
    1100             : 
    1101             :                     /*
    1102             :                      * Complain if the windowfunc's arguments contain any
    1103             :                      * windowfuncs; nested window functions are semantically
    1104             :                      * nonsensical.  (This should have been caught earlier,
    1105             :                      * but we defend against it here anyway.)
    1106             :                      */
    1107        1512 :                     if (nfuncs != winstate->numfuncs)
    1108           0 :                         ereport(ERROR,
    1109             :                                 (errcode(ERRCODE_WINDOWING_ERROR),
    1110             :                                  errmsg("window function calls cannot be nested")));
    1111             :                 }
    1112             :                 else
    1113             :                 {
    1114             :                     /* planner messed up */
    1115           0 :                     elog(ERROR, "WindowFunc found in non-WindowAgg plan node");
    1116             :                 }
    1117             : 
    1118        1512 :                 scratch.opcode = EEOP_WINDOW_FUNC;
    1119        1512 :                 scratch.d.window_func.wfstate = wfstate;
    1120        1512 :                 ExprEvalPushStep(state, &scratch);
    1121        1512 :                 break;
    1122             :             }
    1123             : 
    1124        9762 :         case T_SubscriptingRef:
    1125             :             {
    1126        9762 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
    1127             : 
    1128        9762 :                 ExecInitSubscriptingRef(&scratch, sbsref, state, resv, resnull);
    1129        9762 :                 break;
    1130             :             }
    1131             : 
    1132      694784 :         case T_FuncExpr:
    1133             :             {
    1134      694784 :                 FuncExpr   *func = (FuncExpr *) node;
    1135             : 
    1136      694784 :                 ExecInitFunc(&scratch, node,
    1137             :                              func->args, func->funcid, func->inputcollid,
    1138             :                              state);
    1139      694716 :                 ExprEvalPushStep(state, &scratch);
    1140      694716 :                 break;
    1141             :             }
    1142             : 
    1143      746946 :         case T_OpExpr:
    1144             :             {
    1145      746946 :                 OpExpr     *op = (OpExpr *) node;
    1146             : 
    1147      746946 :                 ExecInitFunc(&scratch, node,
    1148             :                              op->args, op->opfuncid, op->inputcollid,
    1149             :                              state);
    1150      746946 :                 ExprEvalPushStep(state, &scratch);
    1151      746946 :                 break;
    1152             :             }
    1153             : 
    1154         558 :         case T_DistinctExpr:
    1155             :             {
    1156         558 :                 DistinctExpr *op = (DistinctExpr *) node;
    1157             : 
    1158         558 :                 ExecInitFunc(&scratch, node,
    1159             :                              op->args, op->opfuncid, op->inputcollid,
    1160             :                              state);
    1161             : 
    1162             :                 /*
    1163             :                  * Change opcode of call instruction to EEOP_DISTINCT.
    1164             :                  *
    1165             :                  * XXX: historically we've not called the function usage
    1166             :                  * pgstat infrastructure - that seems inconsistent given that
    1167             :                  * we do so for normal function *and* operator evaluation.  If
    1168             :                  * we decided to do that here, we'd probably want separate
    1169             :                  * opcodes for FUSAGE or not.
    1170             :                  */
    1171         558 :                 scratch.opcode = EEOP_DISTINCT;
    1172         558 :                 ExprEvalPushStep(state, &scratch);
    1173         558 :                 break;
    1174             :             }
    1175             : 
    1176         216 :         case T_NullIfExpr:
    1177             :             {
    1178         216 :                 NullIfExpr *op = (NullIfExpr *) node;
    1179             : 
    1180         216 :                 ExecInitFunc(&scratch, node,
    1181             :                              op->args, op->opfuncid, op->inputcollid,
    1182             :                              state);
    1183             : 
    1184             :                 /*
    1185             :                  * Change opcode of call instruction to EEOP_NULLIF.
    1186             :                  *
    1187             :                  * XXX: historically we've not called the function usage
    1188             :                  * pgstat infrastructure - that seems inconsistent given that
    1189             :                  * we do so for normal function *and* operator evaluation.  If
    1190             :                  * we decided to do that here, we'd probably want separate
    1191             :                  * opcodes for FUSAGE or not.
    1192             :                  */
    1193         216 :                 scratch.opcode = EEOP_NULLIF;
    1194         216 :                 ExprEvalPushStep(state, &scratch);
    1195         216 :                 break;
    1196             :             }
    1197             : 
    1198       33194 :         case T_ScalarArrayOpExpr:
    1199             :             {
    1200       33194 :                 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
    1201             :                 Expr       *scalararg;
    1202             :                 Expr       *arrayarg;
    1203             :                 FmgrInfo   *finfo;
    1204             :                 FunctionCallInfo fcinfo;
    1205             :                 AclResult   aclresult;
    1206             :                 FmgrInfo   *hash_finfo;
    1207             :                 FunctionCallInfo hash_fcinfo;
    1208             :                 Oid         cmpfuncid;
    1209             : 
    1210             :                 /*
    1211             :                  * Select the correct comparison function.  When we do hashed
    1212             :                  * NOT IN clauses, the opfuncid will be the inequality
    1213             :                  * comparison function and negfuncid will be set to equality.
    1214             :                  * We need to use the equality function for hash probes.
    1215             :                  */
    1216       33194 :                 if (OidIsValid(opexpr->negfuncid))
    1217             :                 {
    1218             :                     Assert(OidIsValid(opexpr->hashfuncid));
    1219          48 :                     cmpfuncid = opexpr->negfuncid;
    1220             :                 }
    1221             :                 else
    1222       33146 :                     cmpfuncid = opexpr->opfuncid;
    1223             : 
    1224             :                 Assert(list_length(opexpr->args) == 2);
    1225       33194 :                 scalararg = (Expr *) linitial(opexpr->args);
    1226       33194 :                 arrayarg = (Expr *) lsecond(opexpr->args);
    1227             : 
    1228             :                 /* Check permission to call function */
    1229       33194 :                 aclresult = pg_proc_aclcheck(cmpfuncid,
    1230             :                                              GetUserId(),
    1231             :                                              ACL_EXECUTE);
    1232       33194 :                 if (aclresult != ACLCHECK_OK)
    1233           0 :                     aclcheck_error(aclresult, OBJECT_FUNCTION,
    1234           0 :                                    get_func_name(cmpfuncid));
    1235       33194 :                 InvokeFunctionExecuteHook(cmpfuncid);
    1236             : 
    1237       33194 :                 if (OidIsValid(opexpr->hashfuncid))
    1238             :                 {
    1239         136 :                     aclresult = pg_proc_aclcheck(opexpr->hashfuncid,
    1240             :                                                  GetUserId(),
    1241             :                                                  ACL_EXECUTE);
    1242         136 :                     if (aclresult != ACLCHECK_OK)
    1243           0 :                         aclcheck_error(aclresult, OBJECT_FUNCTION,
    1244           0 :                                        get_func_name(opexpr->hashfuncid));
    1245         136 :                     InvokeFunctionExecuteHook(opexpr->hashfuncid);
    1246             :                 }
    1247             : 
    1248             :                 /* Set up the primary fmgr lookup information */
    1249       33194 :                 finfo = palloc0(sizeof(FmgrInfo));
    1250       33194 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
    1251       33194 :                 fmgr_info(cmpfuncid, finfo);
    1252       33194 :                 fmgr_info_set_expr((Node *) node, finfo);
    1253       33194 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
    1254             :                                          opexpr->inputcollid, NULL, NULL);
    1255             : 
    1256             :                 /*
    1257             :                  * If hashfuncid is set, we create a EEOP_HASHED_SCALARARRAYOP
    1258             :                  * step instead of a EEOP_SCALARARRAYOP.  This provides much
    1259             :                  * faster lookup performance than the normal linear search
    1260             :                  * when the number of items in the array is anything but very
    1261             :                  * small.
    1262             :                  */
    1263       33194 :                 if (OidIsValid(opexpr->hashfuncid))
    1264             :                 {
    1265         136 :                     hash_finfo = palloc0(sizeof(FmgrInfo));
    1266         136 :                     hash_fcinfo = palloc0(SizeForFunctionCallInfo(1));
    1267         136 :                     fmgr_info(opexpr->hashfuncid, hash_finfo);
    1268         136 :                     fmgr_info_set_expr((Node *) node, hash_finfo);
    1269         136 :                     InitFunctionCallInfoData(*hash_fcinfo, hash_finfo,
    1270             :                                              1, opexpr->inputcollid, NULL,
    1271             :                                              NULL);
    1272             : 
    1273         136 :                     scratch.d.hashedscalararrayop.hash_finfo = hash_finfo;
    1274         136 :                     scratch.d.hashedscalararrayop.hash_fcinfo_data = hash_fcinfo;
    1275         136 :                     scratch.d.hashedscalararrayop.hash_fn_addr = hash_finfo->fn_addr;
    1276             : 
    1277             :                     /* Evaluate scalar directly into left function argument */
    1278         136 :                     ExecInitExprRec(scalararg, state,
    1279             :                                     &fcinfo->args[0].value, &fcinfo->args[0].isnull);
    1280             : 
    1281             :                     /*
    1282             :                      * Evaluate array argument into our return value.  There's
    1283             :                      * no danger in that, because the return value is
    1284             :                      * guaranteed to be overwritten by
    1285             :                      * EEOP_HASHED_SCALARARRAYOP, and will not be passed to
    1286             :                      * any other expression.
    1287             :                      */
    1288         136 :                     ExecInitExprRec(arrayarg, state, resv, resnull);
    1289             : 
    1290             :                     /* And perform the operation */
    1291         136 :                     scratch.opcode = EEOP_HASHED_SCALARARRAYOP;
    1292         136 :                     scratch.d.hashedscalararrayop.inclause = opexpr->useOr;
    1293         136 :                     scratch.d.hashedscalararrayop.finfo = finfo;
    1294         136 :                     scratch.d.hashedscalararrayop.fcinfo_data = fcinfo;
    1295         136 :                     scratch.d.hashedscalararrayop.fn_addr = finfo->fn_addr;
    1296             : 
    1297         136 :                     scratch.d.hashedscalararrayop.hash_finfo = hash_finfo;
    1298         136 :                     scratch.d.hashedscalararrayop.hash_fcinfo_data = hash_fcinfo;
    1299         136 :                     scratch.d.hashedscalararrayop.hash_fn_addr = hash_finfo->fn_addr;
    1300             : 
    1301         136 :                     ExprEvalPushStep(state, &scratch);
    1302             :                 }
    1303             :                 else
    1304             :                 {
    1305             :                     /* Evaluate scalar directly into left function argument */
    1306       33058 :                     ExecInitExprRec(scalararg, state,
    1307             :                                     &fcinfo->args[0].value,
    1308             :                                     &fcinfo->args[0].isnull);
    1309             : 
    1310             :                     /*
    1311             :                      * Evaluate array argument into our return value.  There's
    1312             :                      * no danger in that, because the return value is
    1313             :                      * guaranteed to be overwritten by EEOP_SCALARARRAYOP, and
    1314             :                      * will not be passed to any other expression.
    1315             :                      */
    1316       33058 :                     ExecInitExprRec(arrayarg, state, resv, resnull);
    1317             : 
    1318             :                     /* And perform the operation */
    1319       33058 :                     scratch.opcode = EEOP_SCALARARRAYOP;
    1320       33058 :                     scratch.d.scalararrayop.element_type = InvalidOid;
    1321       33058 :                     scratch.d.scalararrayop.useOr = opexpr->useOr;
    1322       33058 :                     scratch.d.scalararrayop.finfo = finfo;
    1323       33058 :                     scratch.d.scalararrayop.fcinfo_data = fcinfo;
    1324       33058 :                     scratch.d.scalararrayop.fn_addr = finfo->fn_addr;
    1325       33058 :                     ExprEvalPushStep(state, &scratch);
    1326             :                 }
    1327       33194 :                 break;
    1328             :             }
    1329             : 
    1330       91338 :         case T_BoolExpr:
    1331             :             {
    1332       91338 :                 BoolExpr   *boolexpr = (BoolExpr *) node;
    1333       91338 :                 int         nargs = list_length(boolexpr->args);
    1334       91338 :                 List       *adjust_jumps = NIL;
    1335             :                 int         off;
    1336             :                 ListCell   *lc;
    1337             : 
    1338             :                 /* allocate scratch memory used by all steps of AND/OR */
    1339       91338 :                 if (boolexpr->boolop != NOT_EXPR)
    1340       55930 :                     scratch.d.boolexpr.anynull = (bool *) palloc(sizeof(bool));
    1341             : 
    1342             :                 /*
    1343             :                  * For each argument evaluate the argument itself, then
    1344             :                  * perform the bool operation's appropriate handling.
    1345             :                  *
    1346             :                  * We can evaluate each argument into our result area, since
    1347             :                  * the short-circuiting logic means we only need to remember
    1348             :                  * previous NULL values.
    1349             :                  *
    1350             :                  * AND/OR is split into separate STEP_FIRST (one) / STEP (zero
    1351             :                  * or more) / STEP_LAST (one) steps, as each of those has to
    1352             :                  * perform different work.  The FIRST/LAST split is valid
    1353             :                  * because AND/OR have at least two arguments.
    1354             :                  */
    1355       91338 :                 off = 0;
    1356      246642 :                 foreach(lc, boolexpr->args)
    1357             :                 {
    1358      155304 :                     Expr       *arg = (Expr *) lfirst(lc);
    1359             : 
    1360             :                     /* Evaluate argument into our output variable */
    1361      155304 :                     ExecInitExprRec(arg, state, resv, resnull);
    1362             : 
    1363             :                     /* Perform the appropriate step type */
    1364      155304 :                     switch (boolexpr->boolop)
    1365             :                     {
    1366       77150 :                         case AND_EXPR:
    1367             :                             Assert(nargs >= 2);
    1368             : 
    1369       77150 :                             if (off == 0)
    1370       36182 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_FIRST;
    1371       40968 :                             else if (off + 1 == nargs)
    1372       36182 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_LAST;
    1373             :                             else
    1374        4786 :                                 scratch.opcode = EEOP_BOOL_AND_STEP;
    1375       77150 :                             break;
    1376       42746 :                         case OR_EXPR:
    1377             :                             Assert(nargs >= 2);
    1378             : 
    1379       42746 :                             if (off == 0)
    1380       19748 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_FIRST;
    1381       22998 :                             else if (off + 1 == nargs)
    1382       19748 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_LAST;
    1383             :                             else
    1384        3250 :                                 scratch.opcode = EEOP_BOOL_OR_STEP;
    1385       42746 :                             break;
    1386       35408 :                         case NOT_EXPR:
    1387             :                             Assert(nargs == 1);
    1388             : 
    1389       35408 :                             scratch.opcode = EEOP_BOOL_NOT_STEP;
    1390       35408 :                             break;
    1391           0 :                         default:
    1392           0 :                             elog(ERROR, "unrecognized boolop: %d",
    1393             :                                  (int) boolexpr->boolop);
    1394             :                             break;
    1395             :                     }
    1396             : 
    1397      155304 :                     scratch.d.boolexpr.jumpdone = -1;
    1398      155304 :                     ExprEvalPushStep(state, &scratch);
    1399      155304 :                     adjust_jumps = lappend_int(adjust_jumps,
    1400      155304 :                                                state->steps_len - 1);
    1401      155304 :                     off++;
    1402             :                 }
    1403             : 
    1404             :                 /* adjust jump targets */
    1405      246642 :                 foreach(lc, adjust_jumps)
    1406             :                 {
    1407      155304 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1408             : 
    1409             :                     Assert(as->d.boolexpr.jumpdone == -1);
    1410      155304 :                     as->d.boolexpr.jumpdone = state->steps_len;
    1411             :                 }
    1412             : 
    1413       91338 :                 break;
    1414             :             }
    1415             : 
    1416       86806 :         case T_SubPlan:
    1417             :             {
    1418       86806 :                 SubPlan    *subplan = (SubPlan *) node;
    1419             :                 SubPlanState *sstate;
    1420             : 
    1421       86806 :                 if (!state->parent)
    1422           0 :                     elog(ERROR, "SubPlan found with no parent plan");
    1423             : 
    1424       86806 :                 sstate = ExecInitSubPlan(subplan, state->parent);
    1425             : 
    1426             :                 /* add SubPlanState nodes to state->parent->subPlan */
    1427       86806 :                 state->parent->subPlan = lappend(state->parent->subPlan,
    1428             :                                                  sstate);
    1429             : 
    1430       86806 :                 scratch.opcode = EEOP_SUBPLAN;
    1431       86806 :                 scratch.d.subplan.sstate = sstate;
    1432             : 
    1433       86806 :                 ExprEvalPushStep(state, &scratch);
    1434       86806 :                 break;
    1435             :             }
    1436             : 
    1437        4084 :         case T_FieldSelect:
    1438             :             {
    1439        4084 :                 FieldSelect *fselect = (FieldSelect *) node;
    1440             : 
    1441             :                 /* evaluate row/record argument into result area */
    1442        4084 :                 ExecInitExprRec(fselect->arg, state, resv, resnull);
    1443             : 
    1444             :                 /* and extract field */
    1445        4084 :                 scratch.opcode = EEOP_FIELDSELECT;
    1446        4084 :                 scratch.d.fieldselect.fieldnum = fselect->fieldnum;
    1447        4084 :                 scratch.d.fieldselect.resulttype = fselect->resulttype;
    1448        4084 :                 scratch.d.fieldselect.rowcache.cacheptr = NULL;
    1449             : 
    1450        4084 :                 ExprEvalPushStep(state, &scratch);
    1451        4084 :                 break;
    1452             :             }
    1453             : 
    1454         182 :         case T_FieldStore:
    1455             :             {
    1456         182 :                 FieldStore *fstore = (FieldStore *) node;
    1457             :                 TupleDesc   tupDesc;
    1458             :                 ExprEvalRowtypeCache *rowcachep;
    1459             :                 Datum      *values;
    1460             :                 bool       *nulls;
    1461             :                 int         ncolumns;
    1462             :                 ListCell   *l1,
    1463             :                            *l2;
    1464             : 
    1465             :                 /* find out the number of columns in the composite type */
    1466         182 :                 tupDesc = lookup_rowtype_tupdesc(fstore->resulttype, -1);
    1467         182 :                 ncolumns = tupDesc->natts;
    1468         182 :                 DecrTupleDescRefCount(tupDesc);
    1469             : 
    1470             :                 /* create workspace for column values */
    1471         182 :                 values = (Datum *) palloc(sizeof(Datum) * ncolumns);
    1472         182 :                 nulls = (bool *) palloc(sizeof(bool) * ncolumns);
    1473             : 
    1474             :                 /* create shared composite-type-lookup cache struct */
    1475         182 :                 rowcachep = palloc(sizeof(ExprEvalRowtypeCache));
    1476         182 :                 rowcachep->cacheptr = NULL;
    1477             : 
    1478             :                 /* emit code to evaluate the composite input value */
    1479         182 :                 ExecInitExprRec(fstore->arg, state, resv, resnull);
    1480             : 
    1481             :                 /* next, deform the input tuple into our workspace */
    1482         182 :                 scratch.opcode = EEOP_FIELDSTORE_DEFORM;
    1483         182 :                 scratch.d.fieldstore.fstore = fstore;
    1484         182 :                 scratch.d.fieldstore.rowcache = rowcachep;
    1485         182 :                 scratch.d.fieldstore.values = values;
    1486         182 :                 scratch.d.fieldstore.nulls = nulls;
    1487         182 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1488         182 :                 ExprEvalPushStep(state, &scratch);
    1489             : 
    1490             :                 /* evaluate new field values, store in workspace columns */
    1491         408 :                 forboth(l1, fstore->newvals, l2, fstore->fieldnums)
    1492             :                 {
    1493         226 :                     Expr       *e = (Expr *) lfirst(l1);
    1494         226 :                     AttrNumber  fieldnum = lfirst_int(l2);
    1495             :                     Datum      *save_innermost_caseval;
    1496             :                     bool       *save_innermost_casenull;
    1497             : 
    1498         226 :                     if (fieldnum <= 0 || fieldnum > ncolumns)
    1499           0 :                         elog(ERROR, "field number %d is out of range in FieldStore",
    1500             :                              fieldnum);
    1501             : 
    1502             :                     /*
    1503             :                      * Use the CaseTestExpr mechanism to pass down the old
    1504             :                      * value of the field being replaced; this is needed in
    1505             :                      * case the newval is itself a FieldStore or
    1506             :                      * SubscriptingRef that has to obtain and modify the old
    1507             :                      * value.  It's safe to reuse the CASE mechanism because
    1508             :                      * there cannot be a CASE between here and where the value
    1509             :                      * would be needed, and a field assignment can't be within
    1510             :                      * a CASE either.  (So saving and restoring
    1511             :                      * innermost_caseval is just paranoia, but let's do it
    1512             :                      * anyway.)
    1513             :                      *
    1514             :                      * Another non-obvious point is that it's safe to use the
    1515             :                      * field's values[]/nulls[] entries as both the caseval
    1516             :                      * source and the result address for this subexpression.
    1517             :                      * That's okay only because (1) both FieldStore and
    1518             :                      * SubscriptingRef evaluate their arg or refexpr inputs
    1519             :                      * first, and (2) any such CaseTestExpr is directly the
    1520             :                      * arg or refexpr input.  So any read of the caseval will
    1521             :                      * occur before there's a chance to overwrite it.  Also,
    1522             :                      * if multiple entries in the newvals/fieldnums lists
    1523             :                      * target the same field, they'll effectively be applied
    1524             :                      * left-to-right which is what we want.
    1525             :                      */
    1526         226 :                     save_innermost_caseval = state->innermost_caseval;
    1527         226 :                     save_innermost_casenull = state->innermost_casenull;
    1528         226 :                     state->innermost_caseval = &values[fieldnum - 1];
    1529         226 :                     state->innermost_casenull = &nulls[fieldnum - 1];
    1530             : 
    1531         226 :                     ExecInitExprRec(e, state,
    1532         226 :                                     &values[fieldnum - 1],
    1533         226 :                                     &nulls[fieldnum - 1]);
    1534             : 
    1535         226 :                     state->innermost_caseval = save_innermost_caseval;
    1536         226 :                     state->innermost_casenull = save_innermost_casenull;
    1537             :                 }
    1538             : 
    1539             :                 /* finally, form result tuple */
    1540         182 :                 scratch.opcode = EEOP_FIELDSTORE_FORM;
    1541         182 :                 scratch.d.fieldstore.fstore = fstore;
    1542         182 :                 scratch.d.fieldstore.rowcache = rowcachep;
    1543         182 :                 scratch.d.fieldstore.values = values;
    1544         182 :                 scratch.d.fieldstore.nulls = nulls;
    1545         182 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1546         182 :                 ExprEvalPushStep(state, &scratch);
    1547         182 :                 break;
    1548             :             }
    1549             : 
    1550       52630 :         case T_RelabelType:
    1551             :             {
    1552             :                 /* relabel doesn't need to do anything at runtime */
    1553       52630 :                 RelabelType *relabel = (RelabelType *) node;
    1554             : 
    1555       52630 :                 ExecInitExprRec(relabel->arg, state, resv, resnull);
    1556       52630 :                 break;
    1557             :             }
    1558             : 
    1559       18444 :         case T_CoerceViaIO:
    1560             :             {
    1561       18444 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
    1562             :                 Oid         iofunc;
    1563             :                 bool        typisvarlena;
    1564             :                 Oid         typioparam;
    1565             :                 FunctionCallInfo fcinfo_in;
    1566             : 
    1567             :                 /* evaluate argument into step's result area */
    1568       18444 :                 ExecInitExprRec(iocoerce->arg, state, resv, resnull);
    1569             : 
    1570             :                 /*
    1571             :                  * Prepare both output and input function calls, to be
    1572             :                  * evaluated inside a single evaluation step for speed - this
    1573             :                  * can be a very common operation.
    1574             :                  *
    1575             :                  * We don't check permissions here as a type's input/output
    1576             :                  * function are assumed to be executable by everyone.
    1577             :                  */
    1578       18444 :                 scratch.opcode = EEOP_IOCOERCE;
    1579             : 
    1580             :                 /* lookup the source type's output function */
    1581       18444 :                 scratch.d.iocoerce.finfo_out = palloc0(sizeof(FmgrInfo));
    1582       18444 :                 scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
    1583             : 
    1584       18444 :                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
    1585             :                                   &iofunc, &typisvarlena);
    1586       18444 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_out);
    1587       18444 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_out);
    1588       18444 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_out,
    1589             :                                          scratch.d.iocoerce.finfo_out,
    1590             :                                          1, InvalidOid, NULL, NULL);
    1591             : 
    1592             :                 /* lookup the result type's input function */
    1593       18444 :                 scratch.d.iocoerce.finfo_in = palloc0(sizeof(FmgrInfo));
    1594       18444 :                 scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
    1595             : 
    1596       18444 :                 getTypeInputInfo(iocoerce->resulttype,
    1597             :                                  &iofunc, &typioparam);
    1598       18444 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_in);
    1599       18444 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_in);
    1600       18444 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_in,
    1601             :                                          scratch.d.iocoerce.finfo_in,
    1602             :                                          3, InvalidOid, NULL, NULL);
    1603             : 
    1604             :                 /*
    1605             :                  * We can preload the second and third arguments for the input
    1606             :                  * function, since they're constants.
    1607             :                  */
    1608       18444 :                 fcinfo_in = scratch.d.iocoerce.fcinfo_data_in;
    1609       18444 :                 fcinfo_in->args[1].value = ObjectIdGetDatum(typioparam);
    1610       18444 :                 fcinfo_in->args[1].isnull = false;
    1611       18444 :                 fcinfo_in->args[2].value = Int32GetDatum(-1);
    1612       18444 :                 fcinfo_in->args[2].isnull = false;
    1613             : 
    1614       18444 :                 ExprEvalPushStep(state, &scratch);
    1615       18444 :                 break;
    1616             :             }
    1617             : 
    1618        1360 :         case T_ArrayCoerceExpr:
    1619             :             {
    1620        1360 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    1621             :                 Oid         resultelemtype;
    1622             :                 ExprState  *elemstate;
    1623             : 
    1624             :                 /* evaluate argument into step's result area */
    1625        1360 :                 ExecInitExprRec(acoerce->arg, state, resv, resnull);
    1626             : 
    1627        1360 :                 resultelemtype = get_element_type(acoerce->resulttype);
    1628        1360 :                 if (!OidIsValid(resultelemtype))
    1629           0 :                     ereport(ERROR,
    1630             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1631             :                              errmsg("target type is not an array")));
    1632             : 
    1633             :                 /*
    1634             :                  * Construct a sub-expression for the per-element expression;
    1635             :                  * but don't ready it until after we check it for triviality.
    1636             :                  * We assume it hasn't any Var references, but does have a
    1637             :                  * CaseTestExpr representing the source array element values.
    1638             :                  */
    1639        1360 :                 elemstate = makeNode(ExprState);
    1640        1360 :                 elemstate->expr = acoerce->elemexpr;
    1641        1360 :                 elemstate->parent = state->parent;
    1642        1360 :                 elemstate->ext_params = state->ext_params;
    1643             : 
    1644        1360 :                 elemstate->innermost_caseval = (Datum *) palloc(sizeof(Datum));
    1645        1360 :                 elemstate->innermost_casenull = (bool *) palloc(sizeof(bool));
    1646             : 
    1647        1360 :                 ExecInitExprRec(acoerce->elemexpr, elemstate,
    1648             :                                 &elemstate->resvalue, &elemstate->resnull);
    1649             : 
    1650        1356 :                 if (elemstate->steps_len == 1 &&
    1651        1036 :                     elemstate->steps[0].opcode == EEOP_CASE_TESTVAL)
    1652             :                 {
    1653             :                     /* Trivial, so we need no per-element work at runtime */
    1654        1036 :                     elemstate = NULL;
    1655             :                 }
    1656             :                 else
    1657             :                 {
    1658             :                     /* Not trivial, so append a DONE step */
    1659         320 :                     scratch.opcode = EEOP_DONE;
    1660         320 :                     ExprEvalPushStep(elemstate, &scratch);
    1661             :                     /* and ready the subexpression */
    1662         320 :                     ExecReadyExpr(elemstate);
    1663             :                 }
    1664             : 
    1665        1356 :                 scratch.opcode = EEOP_ARRAYCOERCE;
    1666        1356 :                 scratch.d.arraycoerce.elemexprstate = elemstate;
    1667        1356 :                 scratch.d.arraycoerce.resultelemtype = resultelemtype;
    1668             : 
    1669        1356 :                 if (elemstate)
    1670             :                 {
    1671             :                     /* Set up workspace for array_map */
    1672         320 :                     scratch.d.arraycoerce.amstate =
    1673         320 :                         (ArrayMapState *) palloc0(sizeof(ArrayMapState));
    1674             :                 }
    1675             :                 else
    1676             :                 {
    1677             :                     /* Don't need workspace if there's no subexpression */
    1678        1036 :                     scratch.d.arraycoerce.amstate = NULL;
    1679             :                 }
    1680             : 
    1681        1356 :                 ExprEvalPushStep(state, &scratch);
    1682        1356 :                 break;
    1683             :             }
    1684             : 
    1685         466 :         case T_ConvertRowtypeExpr:
    1686             :             {
    1687         466 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
    1688             :                 ExprEvalRowtypeCache *rowcachep;
    1689             : 
    1690             :                 /* cache structs must be out-of-line for space reasons */
    1691         466 :                 rowcachep = palloc(2 * sizeof(ExprEvalRowtypeCache));
    1692         466 :                 rowcachep[0].cacheptr = NULL;
    1693         466 :                 rowcachep[1].cacheptr = NULL;
    1694             : 
    1695             :                 /* evaluate argument into step's result area */
    1696         466 :                 ExecInitExprRec(convert->arg, state, resv, resnull);
    1697             : 
    1698             :                 /* and push conversion step */
    1699         466 :                 scratch.opcode = EEOP_CONVERT_ROWTYPE;
    1700         466 :                 scratch.d.convert_rowtype.inputtype =
    1701         466 :                     exprType((Node *) convert->arg);
    1702         466 :                 scratch.d.convert_rowtype.outputtype = convert->resulttype;
    1703         466 :                 scratch.d.convert_rowtype.incache = &rowcachep[0];
    1704         466 :                 scratch.d.convert_rowtype.outcache = &rowcachep[1];
    1705         466 :                 scratch.d.convert_rowtype.map = NULL;
    1706             : 
    1707         466 :                 ExprEvalPushStep(state, &scratch);
    1708         466 :                 break;
    1709             :             }
    1710             : 
    1711             :             /* note that CaseWhen expressions are handled within this block */
    1712       76612 :         case T_CaseExpr:
    1713             :             {
    1714       76612 :                 CaseExpr   *caseExpr = (CaseExpr *) node;
    1715       76612 :                 List       *adjust_jumps = NIL;
    1716       76612 :                 Datum      *caseval = NULL;
    1717       76612 :                 bool       *casenull = NULL;
    1718             :                 ListCell   *lc;
    1719             : 
    1720             :                 /*
    1721             :                  * If there's a test expression, we have to evaluate it and
    1722             :                  * save the value where the CaseTestExpr placeholders can find
    1723             :                  * it.
    1724             :                  */
    1725       76612 :                 if (caseExpr->arg != NULL)
    1726             :                 {
    1727             :                     /* Evaluate testexpr into caseval/casenull workspace */
    1728        1854 :                     caseval = palloc(sizeof(Datum));
    1729        1854 :                     casenull = palloc(sizeof(bool));
    1730             : 
    1731        1854 :                     ExecInitExprRec(caseExpr->arg, state,
    1732             :                                     caseval, casenull);
    1733             : 
    1734             :                     /*
    1735             :                      * Since value might be read multiple times, force to R/O
    1736             :                      * - but only if it could be an expanded datum.
    1737             :                      */
    1738        1854 :                     if (get_typlen(exprType((Node *) caseExpr->arg)) == -1)
    1739             :                     {
    1740             :                         /* change caseval in-place */
    1741          38 :                         scratch.opcode = EEOP_MAKE_READONLY;
    1742          38 :                         scratch.resvalue = caseval;
    1743          38 :                         scratch.resnull = casenull;
    1744          38 :                         scratch.d.make_readonly.value = caseval;
    1745          38 :                         scratch.d.make_readonly.isnull = casenull;
    1746          38 :                         ExprEvalPushStep(state, &scratch);
    1747             :                         /* restore normal settings of scratch fields */
    1748          38 :                         scratch.resvalue = resv;
    1749          38 :                         scratch.resnull = resnull;
    1750             :                     }
    1751             :                 }
    1752             : 
    1753             :                 /*
    1754             :                  * Prepare to evaluate each of the WHEN clauses in turn; as
    1755             :                  * soon as one is true we return the value of the
    1756             :                  * corresponding THEN clause.  If none are true then we return
    1757             :                  * the value of the ELSE clause, or NULL if there is none.
    1758             :                  */
    1759      164722 :                 foreach(lc, caseExpr->args)
    1760             :                 {
    1761       88110 :                     CaseWhen   *when = (CaseWhen *) lfirst(lc);
    1762             :                     Datum      *save_innermost_caseval;
    1763             :                     bool       *save_innermost_casenull;
    1764             :                     int         whenstep;
    1765             : 
    1766             :                     /*
    1767             :                      * Make testexpr result available to CaseTestExpr nodes
    1768             :                      * within the condition.  We must save and restore prior
    1769             :                      * setting of innermost_caseval fields, in case this node
    1770             :                      * is itself within a larger CASE.
    1771             :                      *
    1772             :                      * If there's no test expression, we don't actually need
    1773             :                      * to save and restore these fields; but it's less code to
    1774             :                      * just do so unconditionally.
    1775             :                      */
    1776       88110 :                     save_innermost_caseval = state->innermost_caseval;
    1777       88110 :                     save_innermost_casenull = state->innermost_casenull;
    1778       88110 :                     state->innermost_caseval = caseval;
    1779       88110 :                     state->innermost_casenull = casenull;
    1780             : 
    1781             :                     /* evaluate condition into CASE's result variables */
    1782       88110 :                     ExecInitExprRec(when->expr, state, resv, resnull);
    1783             : 
    1784       88110 :                     state->innermost_caseval = save_innermost_caseval;
    1785       88110 :                     state->innermost_casenull = save_innermost_casenull;
    1786             : 
    1787             :                     /* If WHEN result isn't true, jump to next CASE arm */
    1788       88110 :                     scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    1789       88110 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1790       88110 :                     ExprEvalPushStep(state, &scratch);
    1791       88110 :                     whenstep = state->steps_len - 1;
    1792             : 
    1793             :                     /*
    1794             :                      * If WHEN result is true, evaluate THEN result, storing
    1795             :                      * it into the CASE's result variables.
    1796             :                      */
    1797       88110 :                     ExecInitExprRec(when->result, state, resv, resnull);
    1798             : 
    1799             :                     /* Emit JUMP step to jump to end of CASE's code */
    1800       88110 :                     scratch.opcode = EEOP_JUMP;
    1801       88110 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1802       88110 :                     ExprEvalPushStep(state, &scratch);
    1803             : 
    1804             :                     /*
    1805             :                      * Don't know address for that jump yet, compute once the
    1806             :                      * whole CASE expression is built.
    1807             :                      */
    1808       88110 :                     adjust_jumps = lappend_int(adjust_jumps,
    1809       88110 :                                                state->steps_len - 1);
    1810             : 
    1811             :                     /*
    1812             :                      * But we can set WHEN test's jump target now, to make it
    1813             :                      * jump to the next WHEN subexpression or the ELSE.
    1814             :                      */
    1815       88110 :                     state->steps[whenstep].d.jump.jumpdone = state->steps_len;
    1816             :                 }
    1817             : 
    1818             :                 /* transformCaseExpr always adds a default */
    1819             :                 Assert(caseExpr->defresult);
    1820             : 
    1821             :                 /* evaluate ELSE expr into CASE's result variables */
    1822       76612 :                 ExecInitExprRec(caseExpr->defresult, state,
    1823             :                                 resv, resnull);
    1824             : 
    1825             :                 /* adjust jump targets */
    1826      164722 :                 foreach(lc, adjust_jumps)
    1827             :                 {
    1828       88110 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1829             : 
    1830             :                     Assert(as->opcode == EEOP_JUMP);
    1831             :                     Assert(as->d.jump.jumpdone == -1);
    1832       88110 :                     as->d.jump.jumpdone = state->steps_len;
    1833             :                 }
    1834             : 
    1835       76612 :                 break;
    1836             :             }
    1837             : 
    1838        9096 :         case T_CaseTestExpr:
    1839             :             {
    1840             :                 /*
    1841             :                  * Read from location identified by innermost_caseval.  Note
    1842             :                  * that innermost_caseval could be NULL, if this node isn't
    1843             :                  * actually within a CaseExpr, ArrayCoerceExpr, etc structure.
    1844             :                  * That can happen because some parts of the system abuse
    1845             :                  * CaseTestExpr to cause a read of a value externally supplied
    1846             :                  * in econtext->caseValue_datum.  We'll take care of that
    1847             :                  * scenario at runtime.
    1848             :                  */
    1849        9096 :                 scratch.opcode = EEOP_CASE_TESTVAL;
    1850        9096 :                 scratch.d.casetest.value = state->innermost_caseval;
    1851        9096 :                 scratch.d.casetest.isnull = state->innermost_casenull;
    1852             : 
    1853        9096 :                 ExprEvalPushStep(state, &scratch);
    1854        9096 :                 break;
    1855             :             }
    1856             : 
    1857       27108 :         case T_ArrayExpr:
    1858             :             {
    1859       27108 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
    1860       27108 :                 int         nelems = list_length(arrayexpr->elements);
    1861             :                 ListCell   *lc;
    1862             :                 int         elemoff;
    1863             : 
    1864             :                 /*
    1865             :                  * Evaluate by computing each element, and then forming the
    1866             :                  * array.  Elements are computed into scratch arrays
    1867             :                  * associated with the ARRAYEXPR step.
    1868             :                  */
    1869       27108 :                 scratch.opcode = EEOP_ARRAYEXPR;
    1870       27108 :                 scratch.d.arrayexpr.elemvalues =
    1871       27108 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    1872       27108 :                 scratch.d.arrayexpr.elemnulls =
    1873       27108 :                     (bool *) palloc(sizeof(bool) * nelems);
    1874       27108 :                 scratch.d.arrayexpr.nelems = nelems;
    1875             : 
    1876             :                 /* fill remaining fields of step */
    1877       27108 :                 scratch.d.arrayexpr.multidims = arrayexpr->multidims;
    1878       27108 :                 scratch.d.arrayexpr.elemtype = arrayexpr->element_typeid;
    1879             : 
    1880             :                 /* do one-time catalog lookup for type info */
    1881       27108 :                 get_typlenbyvalalign(arrayexpr->element_typeid,
    1882             :                                      &scratch.d.arrayexpr.elemlength,
    1883             :                                      &scratch.d.arrayexpr.elembyval,
    1884             :                                      &scratch.d.arrayexpr.elemalign);
    1885             : 
    1886             :                 /* prepare to evaluate all arguments */
    1887       27108 :                 elemoff = 0;
    1888      106234 :                 foreach(lc, arrayexpr->elements)
    1889             :                 {
    1890       79126 :                     Expr       *e = (Expr *) lfirst(lc);
    1891             : 
    1892       79126 :                     ExecInitExprRec(e, state,
    1893       79126 :                                     &scratch.d.arrayexpr.elemvalues[elemoff],
    1894       79126 :                                     &scratch.d.arrayexpr.elemnulls[elemoff]);
    1895       79126 :                     elemoff++;
    1896             :                 }
    1897             : 
    1898             :                 /* and then collect all into an array */
    1899       27108 :                 ExprEvalPushStep(state, &scratch);
    1900       27108 :                 break;
    1901             :             }
    1902             : 
    1903        3456 :         case T_RowExpr:
    1904             :             {
    1905        3456 :                 RowExpr    *rowexpr = (RowExpr *) node;
    1906        3456 :                 int         nelems = list_length(rowexpr->args);
    1907             :                 TupleDesc   tupdesc;
    1908             :                 int         i;
    1909             :                 ListCell   *l;
    1910             : 
    1911             :                 /* Build tupdesc to describe result tuples */
    1912        3456 :                 if (rowexpr->row_typeid == RECORDOID)
    1913             :                 {
    1914             :                     /* generic record, use types of given expressions */
    1915        1798 :                     tupdesc = ExecTypeFromExprList(rowexpr->args);
    1916             :                 }
    1917             :                 else
    1918             :                 {
    1919             :                     /* it's been cast to a named type, use that */
    1920        1658 :                     tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
    1921             :                 }
    1922             :                 /* In either case, adopt RowExpr's column aliases */
    1923        3456 :                 ExecTypeSetColNames(tupdesc, rowexpr->colnames);
    1924             :                 /* Bless the tupdesc in case it's now of type RECORD */
    1925        3456 :                 BlessTupleDesc(tupdesc);
    1926             : 
    1927             :                 /*
    1928             :                  * In the named-type case, the tupdesc could have more columns
    1929             :                  * than are in the args list, since the type might have had
    1930             :                  * columns added since the ROW() was parsed.  We want those
    1931             :                  * extra columns to go to nulls, so we make sure that the
    1932             :                  * workspace arrays are large enough and then initialize any
    1933             :                  * extra columns to read as NULLs.
    1934             :                  */
    1935             :                 Assert(nelems <= tupdesc->natts);
    1936        3456 :                 nelems = Max(nelems, tupdesc->natts);
    1937             : 
    1938             :                 /*
    1939             :                  * Evaluate by first building datums for each field, and then
    1940             :                  * a final step forming the composite datum.
    1941             :                  */
    1942        3456 :                 scratch.opcode = EEOP_ROW;
    1943        3456 :                 scratch.d.row.tupdesc = tupdesc;
    1944             : 
    1945             :                 /* space for the individual field datums */
    1946        3456 :                 scratch.d.row.elemvalues =
    1947        3456 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    1948        3456 :                 scratch.d.row.elemnulls =
    1949        3456 :                     (bool *) palloc(sizeof(bool) * nelems);
    1950             :                 /* as explained above, make sure any extra columns are null */
    1951        3456 :                 memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
    1952             : 
    1953             :                 /* Set up evaluation, skipping any deleted columns */
    1954        3456 :                 i = 0;
    1955       12804 :                 foreach(l, rowexpr->args)
    1956             :                 {
    1957        9348 :                     Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    1958        9348 :                     Expr       *e = (Expr *) lfirst(l);
    1959             : 
    1960        9348 :                     if (!att->attisdropped)
    1961             :                     {
    1962             :                         /*
    1963             :                          * Guard against ALTER COLUMN TYPE on rowtype since
    1964             :                          * the RowExpr was created.  XXX should we check
    1965             :                          * typmod too?  Not sure we can be sure it'll be the
    1966             :                          * same.
    1967             :                          */
    1968        9330 :                         if (exprType((Node *) e) != att->atttypid)
    1969           0 :                             ereport(ERROR,
    1970             :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1971             :                                      errmsg("ROW() column has type %s instead of type %s",
    1972             :                                             format_type_be(exprType((Node *) e)),
    1973             :                                             format_type_be(att->atttypid))));
    1974             :                     }
    1975             :                     else
    1976             :                     {
    1977             :                         /*
    1978             :                          * Ignore original expression and insert a NULL. We
    1979             :                          * don't really care what type of NULL it is, so
    1980             :                          * always make an int4 NULL.
    1981             :                          */
    1982          18 :                         e = (Expr *) makeNullConst(INT4OID, -1, InvalidOid);
    1983             :                     }
    1984             : 
    1985             :                     /* Evaluate column expr into appropriate workspace slot */
    1986        9348 :                     ExecInitExprRec(e, state,
    1987        9348 :                                     &scratch.d.row.elemvalues[i],
    1988        9348 :                                     &scratch.d.row.elemnulls[i]);
    1989        9348 :                     i++;
    1990             :                 }
    1991             : 
    1992             :                 /* And finally build the row value */
    1993        3456 :                 ExprEvalPushStep(state, &scratch);
    1994        3456 :                 break;
    1995             :             }
    1996             : 
    1997         112 :         case T_RowCompareExpr:
    1998             :             {
    1999         112 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
    2000         112 :                 int         nopers = list_length(rcexpr->opnos);
    2001         112 :                 List       *adjust_jumps = NIL;
    2002             :                 ListCell   *l_left_expr,
    2003             :                            *l_right_expr,
    2004             :                            *l_opno,
    2005             :                            *l_opfamily,
    2006             :                            *l_inputcollid;
    2007             :                 ListCell   *lc;
    2008             : 
    2009             :                 /*
    2010             :                  * Iterate over each field, prepare comparisons.  To handle
    2011             :                  * NULL results, prepare jumps to after the expression.  If a
    2012             :                  * comparison yields a != 0 result, jump to the final step.
    2013             :                  */
    2014             :                 Assert(list_length(rcexpr->largs) == nopers);
    2015             :                 Assert(list_length(rcexpr->rargs) == nopers);
    2016             :                 Assert(list_length(rcexpr->opfamilies) == nopers);
    2017             :                 Assert(list_length(rcexpr->inputcollids) == nopers);
    2018             : 
    2019         372 :                 forfive(l_left_expr, rcexpr->largs,
    2020             :                         l_right_expr, rcexpr->rargs,
    2021             :                         l_opno, rcexpr->opnos,
    2022             :                         l_opfamily, rcexpr->opfamilies,
    2023             :                         l_inputcollid, rcexpr->inputcollids)
    2024             :                 {
    2025         260 :                     Expr       *left_expr = (Expr *) lfirst(l_left_expr);
    2026         260 :                     Expr       *right_expr = (Expr *) lfirst(l_right_expr);
    2027         260 :                     Oid         opno = lfirst_oid(l_opno);
    2028         260 :                     Oid         opfamily = lfirst_oid(l_opfamily);
    2029         260 :                     Oid         inputcollid = lfirst_oid(l_inputcollid);
    2030             :                     int         strategy;
    2031             :                     Oid         lefttype;
    2032             :                     Oid         righttype;
    2033             :                     Oid         proc;
    2034             :                     FmgrInfo   *finfo;
    2035             :                     FunctionCallInfo fcinfo;
    2036             : 
    2037         260 :                     get_op_opfamily_properties(opno, opfamily, false,
    2038             :                                                &strategy,
    2039             :                                                &lefttype,
    2040             :                                                &righttype);
    2041         260 :                     proc = get_opfamily_proc(opfamily,
    2042             :                                              lefttype,
    2043             :                                              righttype,
    2044             :                                              BTORDER_PROC);
    2045         260 :                     if (!OidIsValid(proc))
    2046           0 :                         elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
    2047             :                              BTORDER_PROC, lefttype, righttype, opfamily);
    2048             : 
    2049             :                     /* Set up the primary fmgr lookup information */
    2050         260 :                     finfo = palloc0(sizeof(FmgrInfo));
    2051         260 :                     fcinfo = palloc0(SizeForFunctionCallInfo(2));
    2052         260 :                     fmgr_info(proc, finfo);
    2053         260 :                     fmgr_info_set_expr((Node *) node, finfo);
    2054         260 :                     InitFunctionCallInfoData(*fcinfo, finfo, 2,
    2055             :                                              inputcollid, NULL, NULL);
    2056             : 
    2057             :                     /*
    2058             :                      * If we enforced permissions checks on index support
    2059             :                      * functions, we'd need to make a check here.  But the
    2060             :                      * index support machinery doesn't do that, and thus
    2061             :                      * neither does this code.
    2062             :                      */
    2063             : 
    2064             :                     /* evaluate left and right args directly into fcinfo */
    2065         260 :                     ExecInitExprRec(left_expr, state,
    2066             :                                     &fcinfo->args[0].value, &fcinfo->args[0].isnull);
    2067         260 :                     ExecInitExprRec(right_expr, state,
    2068             :                                     &fcinfo->args[1].value, &fcinfo->args[1].isnull);
    2069             : 
    2070         260 :                     scratch.opcode = EEOP_ROWCOMPARE_STEP;
    2071         260 :                     scratch.d.rowcompare_step.finfo = finfo;
    2072         260 :                     scratch.d.rowcompare_step.fcinfo_data = fcinfo;
    2073         260 :                     scratch.d.rowcompare_step.fn_addr = finfo->fn_addr;
    2074             :                     /* jump targets filled below */
    2075         260 :                     scratch.d.rowcompare_step.jumpnull = -1;
    2076         260 :                     scratch.d.rowcompare_step.jumpdone = -1;
    2077             : 
    2078         260 :                     ExprEvalPushStep(state, &scratch);
    2079         260 :                     adjust_jumps = lappend_int(adjust_jumps,
    2080         260 :                                                state->steps_len - 1);
    2081             :                 }
    2082             : 
    2083             :                 /*
    2084             :                  * We could have a zero-column rowtype, in which case the rows
    2085             :                  * necessarily compare equal.
    2086             :                  */
    2087         112 :                 if (nopers == 0)
    2088             :                 {
    2089           0 :                     scratch.opcode = EEOP_CONST;
    2090           0 :                     scratch.d.constval.value = Int32GetDatum(0);
    2091           0 :                     scratch.d.constval.isnull = false;
    2092           0 :                     ExprEvalPushStep(state, &scratch);
    2093             :                 }
    2094             : 
    2095             :                 /* Finally, examine the last comparison result */
    2096         112 :                 scratch.opcode = EEOP_ROWCOMPARE_FINAL;
    2097         112 :                 scratch.d.rowcompare_final.rctype = rcexpr->rctype;
    2098         112 :                 ExprEvalPushStep(state, &scratch);
    2099             : 
    2100             :                 /* adjust jump targets */
    2101         372 :                 foreach(lc, adjust_jumps)
    2102             :                 {
    2103         260 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    2104             : 
    2105             :                     Assert(as->opcode == EEOP_ROWCOMPARE_STEP);
    2106             :                     Assert(as->d.rowcompare_step.jumpdone == -1);
    2107             :                     Assert(as->d.rowcompare_step.jumpnull == -1);
    2108             : 
    2109             :                     /* jump to comparison evaluation */
    2110         260 :                     as->d.rowcompare_step.jumpdone = state->steps_len - 1;
    2111             :                     /* jump to the following expression */
    2112         260 :                     as->d.rowcompare_step.jumpnull = state->steps_len;
    2113             :                 }
    2114             : 
    2115         112 :                 break;
    2116             :             }
    2117             : 
    2118       15490 :         case T_CoalesceExpr:
    2119             :             {
    2120       15490 :                 CoalesceExpr *coalesce = (CoalesceExpr *) node;
    2121       15490 :                 List       *adjust_jumps = NIL;
    2122             :                 ListCell   *lc;
    2123             : 
    2124             :                 /* We assume there's at least one arg */
    2125             :                 Assert(coalesce->args != NIL);
    2126             : 
    2127             :                 /*
    2128             :                  * Prepare evaluation of all coalesced arguments, after each
    2129             :                  * one push a step that short-circuits if not null.
    2130             :                  */
    2131       46462 :                 foreach(lc, coalesce->args)
    2132             :                 {
    2133       30972 :                     Expr       *e = (Expr *) lfirst(lc);
    2134             : 
    2135             :                     /* evaluate argument, directly into result datum */
    2136       30972 :                     ExecInitExprRec(e, state, resv, resnull);
    2137             : 
    2138             :                     /* if it's not null, skip to end of COALESCE expr */
    2139       30972 :                     scratch.opcode = EEOP_JUMP_IF_NOT_NULL;
    2140       30972 :                     scratch.d.jump.jumpdone = -1;   /* adjust later */
    2141       30972 :                     ExprEvalPushStep(state, &scratch);
    2142             : 
    2143       30972 :                     adjust_jumps = lappend_int(adjust_jumps,
    2144       30972 :                                                state->steps_len - 1);
    2145             :                 }
    2146             : 
    2147             :                 /*
    2148             :                  * No need to add a constant NULL return - we only can get to
    2149             :                  * the end of the expression if a NULL already is being
    2150             :                  * returned.
    2151             :                  */
    2152             : 
    2153             :                 /* adjust jump targets */
    2154       46462 :                 foreach(lc, adjust_jumps)
    2155             :                 {
    2156       30972 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    2157             : 
    2158             :                     Assert(as->opcode == EEOP_JUMP_IF_NOT_NULL);
    2159             :                     Assert(as->d.jump.jumpdone == -1);
    2160       30972 :                     as->d.jump.jumpdone = state->steps_len;
    2161             :                 }
    2162             : 
    2163       15490 :                 break;
    2164             :             }
    2165             : 
    2166        2252 :         case T_MinMaxExpr:
    2167             :             {
    2168        2252 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
    2169        2252 :                 int         nelems = list_length(minmaxexpr->args);
    2170             :                 TypeCacheEntry *typentry;
    2171             :                 FmgrInfo   *finfo;
    2172             :                 FunctionCallInfo fcinfo;
    2173             :                 ListCell   *lc;
    2174             :                 int         off;
    2175             : 
    2176             :                 /* Look up the btree comparison function for the datatype */
    2177        2252 :                 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
    2178             :                                              TYPECACHE_CMP_PROC);
    2179        2252 :                 if (!OidIsValid(typentry->cmp_proc))
    2180           0 :                     ereport(ERROR,
    2181             :                             (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2182             :                              errmsg("could not identify a comparison function for type %s",
    2183             :                                     format_type_be(minmaxexpr->minmaxtype))));
    2184             : 
    2185             :                 /*
    2186             :                  * If we enforced permissions checks on index support
    2187             :                  * functions, we'd need to make a check here.  But the index
    2188             :                  * support machinery doesn't do that, and thus neither does
    2189             :                  * this code.
    2190             :                  */
    2191             : 
    2192             :                 /* Perform function lookup */
    2193        2252 :                 finfo = palloc0(sizeof(FmgrInfo));
    2194        2252 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
    2195        2252 :                 fmgr_info(typentry->cmp_proc, finfo);
    2196        2252 :                 fmgr_info_set_expr((Node *) node, finfo);
    2197        2252 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
    2198             :                                          minmaxexpr->inputcollid, NULL, NULL);
    2199             : 
    2200        2252 :                 scratch.opcode = EEOP_MINMAX;
    2201             :                 /* allocate space to store arguments */
    2202        2252 :                 scratch.d.minmax.values =
    2203        2252 :                     (Datum *) palloc(sizeof(Datum) * nelems);
    2204        2252 :                 scratch.d.minmax.nulls =
    2205        2252 :                     (bool *) palloc(sizeof(bool) * nelems);
    2206        2252 :                 scratch.d.minmax.nelems = nelems;
    2207             : 
    2208        2252 :                 scratch.d.minmax.op = minmaxexpr->op;
    2209        2252 :                 scratch.d.minmax.finfo = finfo;
    2210        2252 :                 scratch.d.minmax.fcinfo_data = fcinfo;
    2211             : 
    2212             :                 /* evaluate expressions into minmax->values/nulls */
    2213        2252 :                 off = 0;
    2214        6828 :                 foreach(lc, minmaxexpr->args)
    2215             :                 {
    2216        4576 :                     Expr       *e = (Expr *) lfirst(lc);
    2217             : 
    2218        4576 :                     ExecInitExprRec(e, state,
    2219        4576 :                                     &scratch.d.minmax.values[off],
    2220        4576 :                                     &scratch.d.minmax.nulls[off]);
    2221        4576 :                     off++;
    2222             :                 }
    2223             : 
    2224             :                 /* and push the final comparison */
    2225        2252 :                 ExprEvalPushStep(state, &scratch);
    2226        2252 :                 break;
    2227             :             }
    2228             : 
    2229        2244 :         case T_SQLValueFunction:
    2230             :             {
    2231        2244 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
    2232             : 
    2233        2244 :                 scratch.opcode = EEOP_SQLVALUEFUNCTION;
    2234        2244 :                 scratch.d.sqlvaluefunction.svf = svf;
    2235             : 
    2236        2244 :                 ExprEvalPushStep(state, &scratch);
    2237        2244 :                 break;
    2238             :             }
    2239             : 
    2240         356 :         case T_XmlExpr:
    2241             :             {
    2242         356 :                 XmlExpr    *xexpr = (XmlExpr *) node;
    2243         356 :                 int         nnamed = list_length(xexpr->named_args);
    2244         356 :                 int         nargs = list_length(xexpr->args);
    2245             :                 int         off;
    2246             :                 ListCell   *arg;
    2247             : 
    2248         356 :                 scratch.opcode = EEOP_XMLEXPR;
    2249         356 :                 scratch.d.xmlexpr.xexpr = xexpr;
    2250             : 
    2251             :                 /* allocate space for storing all the arguments */
    2252         356 :                 if (nnamed)
    2253             :                 {
    2254          40 :                     scratch.d.xmlexpr.named_argvalue =
    2255          40 :                         (Datum *) palloc(sizeof(Datum) * nnamed);
    2256          40 :                     scratch.d.xmlexpr.named_argnull =
    2257          40 :                         (bool *) palloc(sizeof(bool) * nnamed);
    2258             :                 }
    2259             :                 else
    2260             :                 {
    2261         316 :                     scratch.d.xmlexpr.named_argvalue = NULL;
    2262         316 :                     scratch.d.xmlexpr.named_argnull = NULL;
    2263             :                 }
    2264             : 
    2265         356 :                 if (nargs)
    2266             :                 {
    2267         300 :                     scratch.d.xmlexpr.argvalue =
    2268         300 :                         (Datum *) palloc(sizeof(Datum) * nargs);
    2269         300 :                     scratch.d.xmlexpr.argnull =
    2270         300 :                         (bool *) palloc(sizeof(bool) * nargs);
    2271             :                 }
    2272             :                 else
    2273             :                 {
    2274          56 :                     scratch.d.xmlexpr.argvalue = NULL;
    2275          56 :                     scratch.d.xmlexpr.argnull = NULL;
    2276             :                 }
    2277             : 
    2278             :                 /* prepare argument execution */
    2279         356 :                 off = 0;
    2280         468 :                 foreach(arg, xexpr->named_args)
    2281             :                 {
    2282         112 :                     Expr       *e = (Expr *) lfirst(arg);
    2283             : 
    2284         112 :                     ExecInitExprRec(e, state,
    2285         112 :                                     &scratch.d.xmlexpr.named_argvalue[off],
    2286         112 :                                     &scratch.d.xmlexpr.named_argnull[off]);
    2287         112 :                     off++;
    2288             :                 }
    2289             : 
    2290         356 :                 off = 0;
    2291         868 :                 foreach(arg, xexpr->args)
    2292             :                 {
    2293         512 :                     Expr       *e = (Expr *) lfirst(arg);
    2294             : 
    2295         512 :                     ExecInitExprRec(e, state,
    2296         512 :                                     &scratch.d.xmlexpr.argvalue[off],
    2297         512 :                                     &scratch.d.xmlexpr.argnull[off]);
    2298         512 :                     off++;
    2299             :                 }
    2300             : 
    2301             :                 /* and evaluate the actual XML expression */
    2302         356 :                 ExprEvalPushStep(state, &scratch);
    2303         356 :                 break;
    2304             :             }
    2305             : 
    2306       18224 :         case T_NullTest:
    2307             :             {
    2308       18224 :                 NullTest   *ntest = (NullTest *) node;
    2309             : 
    2310       18224 :                 if (ntest->nulltesttype == IS_NULL)
    2311             :                 {
    2312        4938 :                     if (ntest->argisrow)
    2313         112 :                         scratch.opcode = EEOP_NULLTEST_ROWISNULL;
    2314             :                     else
    2315        4826 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    2316             :                 }
    2317       13286 :                 else if (ntest->nulltesttype == IS_NOT_NULL)
    2318             :                 {
    2319       13286 :                     if (ntest->argisrow)
    2320         110 :                         scratch.opcode = EEOP_NULLTEST_ROWISNOTNULL;
    2321             :                     else
    2322       13176 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2323             :                 }
    2324             :                 else
    2325             :                 {
    2326           0 :                     elog(ERROR, "unrecognized nulltesttype: %d",
    2327             :                          (int) ntest->nulltesttype);
    2328             :                 }
    2329             :                 /* initialize cache in case it's a row test */
    2330       18224 :                 scratch.d.nulltest_row.rowcache.cacheptr = NULL;
    2331             : 
    2332             :                 /* first evaluate argument into result variable */
    2333       18224 :                 ExecInitExprRec(ntest->arg, state,
    2334             :                                 resv, resnull);
    2335             : 
    2336             :                 /* then push the test of that argument */
    2337       18224 :                 ExprEvalPushStep(state, &scratch);
    2338       18224 :                 break;
    2339             :             }
    2340             : 
    2341         218 :         case T_BooleanTest:
    2342             :             {
    2343         218 :                 BooleanTest *btest = (BooleanTest *) node;
    2344             : 
    2345             :                 /*
    2346             :                  * Evaluate argument, directly into result datum.  That's ok,
    2347             :                  * because resv/resnull is definitely not used anywhere else,
    2348             :                  * and will get overwritten by the below EEOP_BOOLTEST_IS_*
    2349             :                  * step.
    2350             :                  */
    2351         218 :                 ExecInitExprRec(btest->arg, state, resv, resnull);
    2352             : 
    2353         218 :                 switch (btest->booltesttype)
    2354             :                 {
    2355          52 :                     case IS_TRUE:
    2356          52 :                         scratch.opcode = EEOP_BOOLTEST_IS_TRUE;
    2357          52 :                         break;
    2358          90 :                     case IS_NOT_TRUE:
    2359          90 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_TRUE;
    2360          90 :                         break;
    2361          24 :                     case IS_FALSE:
    2362          24 :                         scratch.opcode = EEOP_BOOLTEST_IS_FALSE;
    2363          24 :                         break;
    2364          16 :                     case IS_NOT_FALSE:
    2365          16 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_FALSE;
    2366          16 :                         break;
    2367          20 :                     case IS_UNKNOWN:
    2368             :                         /* Same as scalar IS NULL test */
    2369          20 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    2370          20 :                         break;
    2371          16 :                     case IS_NOT_UNKNOWN:
    2372             :                         /* Same as scalar IS NOT NULL test */
    2373          16 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2374          16 :                         break;
    2375           0 :                     default:
    2376           0 :                         elog(ERROR, "unrecognized booltesttype: %d",
    2377             :                              (int) btest->booltesttype);
    2378             :                 }
    2379             : 
    2380         218 :                 ExprEvalPushStep(state, &scratch);
    2381         218 :                 break;
    2382             :             }
    2383             : 
    2384       35140 :         case T_CoerceToDomain:
    2385             :             {
    2386       35140 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
    2387             : 
    2388       35140 :                 ExecInitCoerceToDomain(&scratch, ctest, state,
    2389             :                                        resv, resnull);
    2390       35140 :                 break;
    2391             :             }
    2392             : 
    2393       38422 :         case T_CoerceToDomainValue:
    2394             :             {
    2395             :                 /*
    2396             :                  * Read from location identified by innermost_domainval.  Note
    2397             :                  * that innermost_domainval could be NULL, if we're compiling
    2398             :                  * a standalone domain check rather than one embedded in a
    2399             :                  * larger expression.  In that case we must read from
    2400             :                  * econtext->domainValue_datum.  We'll take care of that
    2401             :                  * scenario at runtime.
    2402             :                  */
    2403       38422 :                 scratch.opcode = EEOP_DOMAIN_TESTVAL;
    2404             :                 /* we share instruction union variant with case testval */
    2405       38422 :                 scratch.d.casetest.value = state->innermost_domainval;
    2406       38422 :                 scratch.d.casetest.isnull = state->innermost_domainnull;
    2407             : 
    2408       38422 :                 ExprEvalPushStep(state, &scratch);
    2409       38422 :                 break;
    2410             :             }
    2411             : 
    2412           2 :         case T_CurrentOfExpr:
    2413             :             {
    2414           2 :                 scratch.opcode = EEOP_CURRENTOFEXPR;
    2415           2 :                 ExprEvalPushStep(state, &scratch);
    2416           2 :                 break;
    2417             :             }
    2418             : 
    2419         226 :         case T_NextValueExpr:
    2420             :             {
    2421         226 :                 NextValueExpr *nve = (NextValueExpr *) node;
    2422             : 
    2423         226 :                 scratch.opcode = EEOP_NEXTVALUEEXPR;
    2424         226 :                 scratch.d.nextvalueexpr.seqid = nve->seqid;
    2425         226 :                 scratch.d.nextvalueexpr.seqtypid = nve->typeId;
    2426             : 
    2427         226 :                 ExprEvalPushStep(state, &scratch);
    2428         226 :                 break;
    2429             :             }
    2430             : 
    2431           0 :         default:
    2432           0 :             elog(ERROR, "unrecognized node type: %d",
    2433             :                  (int) nodeTag(node));
    2434             :             break;
    2435             :     }
    2436     4950648 : }
    2437             : 
    2438             : /*
    2439             :  * Add another expression evaluation step to ExprState->steps.
    2440             :  *
    2441             :  * Note that this potentially re-allocates es->steps, therefore no pointer
    2442             :  * into that array may be used while the expression is still being built.
    2443             :  */
    2444             : void
    2445    12172506 : ExprEvalPushStep(ExprState *es, const ExprEvalStep *s)
    2446             : {
    2447    12172506 :     if (es->steps_alloc == 0)
    2448             :     {
    2449     2355772 :         es->steps_alloc = 16;
    2450     2355772 :         es->steps = palloc(sizeof(ExprEvalStep) * es->steps_alloc);
    2451             :     }
    2452     9816734 :     else if (es->steps_alloc == es->steps_len)
    2453             :     {
    2454      111380 :         es->steps_alloc *= 2;
    2455      111380 :         es->steps = repalloc(es->steps,
    2456      111380 :                              sizeof(ExprEvalStep) * es->steps_alloc);
    2457             :     }
    2458             : 
    2459    12172506 :     memcpy(&es->steps[es->steps_len++], s, sizeof(ExprEvalStep));
    2460    12172506 : }
    2461             : 
    2462             : /*
    2463             :  * Perform setup necessary for the evaluation of a function-like expression,
    2464             :  * appending argument evaluation steps to the steps list in *state, and
    2465             :  * setting up *scratch so it is ready to be pushed.
    2466             :  *
    2467             :  * *scratch is not pushed here, so that callers may override the opcode,
    2468             :  * which is useful for function-like cases like DISTINCT.
    2469             :  */
    2470             : static void
    2471     1442504 : ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args, Oid funcid,
    2472             :              Oid inputcollid, ExprState *state)
    2473             : {
    2474     1442504 :     int         nargs = list_length(args);
    2475             :     AclResult   aclresult;
    2476             :     FmgrInfo   *flinfo;
    2477             :     FunctionCallInfo fcinfo;
    2478             :     int         argno;
    2479             :     ListCell   *lc;
    2480             : 
    2481             :     /* Check permission to call function */
    2482     1442504 :     aclresult = pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE);
    2483     1442504 :     if (aclresult != ACLCHECK_OK)
    2484          68 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(funcid));
    2485     1442436 :     InvokeFunctionExecuteHook(funcid);
    2486             : 
    2487             :     /*
    2488             :      * Safety check on nargs.  Under normal circumstances this should never
    2489             :      * fail, as parser should check sooner.  But possibly it might fail if
    2490             :      * server has been compiled with FUNC_MAX_ARGS smaller than some functions
    2491             :      * declared in pg_proc?
    2492             :      */
    2493     1442436 :     if (nargs > FUNC_MAX_ARGS)
    2494           0 :         ereport(ERROR,
    2495             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
    2496             :                  errmsg_plural("cannot pass more than %d argument to a function",
    2497             :                                "cannot pass more than %d arguments to a function",
    2498             :                                FUNC_MAX_ARGS,
    2499             :                                FUNC_MAX_ARGS)));
    2500             : 
    2501             :     /* Allocate function lookup data and parameter workspace for this call */
    2502     1442436 :     scratch->d.func.finfo = palloc0(sizeof(FmgrInfo));
    2503     1442436 :     scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
    2504     1442436 :     flinfo = scratch->d.func.finfo;
    2505     1442436 :     fcinfo = scratch->d.func.fcinfo_data;
    2506             : 
    2507             :     /* Set up the primary fmgr lookup information */
    2508     1442436 :     fmgr_info(funcid, flinfo);
    2509     1442436 :     fmgr_info_set_expr((Node *) node, flinfo);
    2510             : 
    2511             :     /* Initialize function call parameter structure too */
    2512     1442436 :     InitFunctionCallInfoData(*fcinfo, flinfo,
    2513             :                              nargs, inputcollid, NULL, NULL);
    2514             : 
    2515             :     /* Keep extra copies of this info to save an indirection at runtime */
    2516     1442436 :     scratch->d.func.fn_addr = flinfo->fn_addr;
    2517     1442436 :     scratch->d.func.nargs = nargs;
    2518             : 
    2519             :     /* We only support non-set functions here */
    2520     1442436 :     if (flinfo->fn_retset)
    2521           0 :         ereport(ERROR,
    2522             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2523             :                  errmsg("set-valued function called in context that cannot accept a set"),
    2524             :                  state->parent ?
    2525             :                  executor_errposition(state->parent->state,
    2526             :                                       exprLocation((Node *) node)) : 0));
    2527             : 
    2528             :     /* Build code to evaluate arguments directly into the fcinfo struct */
    2529     1442436 :     argno = 0;
    2530     3792226 :     foreach(lc, args)
    2531             :     {
    2532     2349790 :         Expr       *arg = (Expr *) lfirst(lc);
    2533             : 
    2534     2349790 :         if (IsA(arg, Const))
    2535             :         {
    2536             :             /*
    2537             :              * Don't evaluate const arguments every round; especially
    2538             :              * interesting for constants in comparisons.
    2539             :              */
    2540      874866 :             Const      *con = (Const *) arg;
    2541             : 
    2542      874866 :             fcinfo->args[argno].value = con->constvalue;
    2543      874866 :             fcinfo->args[argno].isnull = con->constisnull;
    2544             :         }
    2545             :         else
    2546             :         {
    2547     1474924 :             ExecInitExprRec(arg, state,
    2548             :                             &fcinfo->args[argno].value,
    2549             :                             &fcinfo->args[argno].isnull);
    2550             :         }
    2551     2349790 :         argno++;
    2552             :     }
    2553             : 
    2554             :     /* Insert appropriate opcode depending on strictness and stats level */
    2555     1442436 :     if (pgstat_track_functions <= flinfo->fn_stats)
    2556             :     {
    2557     1442436 :         if (flinfo->fn_strict && nargs > 0)
    2558     1291182 :             scratch->opcode = EEOP_FUNCEXPR_STRICT;
    2559             :         else
    2560      151254 :             scratch->opcode = EEOP_FUNCEXPR;
    2561             :     }
    2562             :     else
    2563             :     {
    2564           0 :         if (flinfo->fn_strict && nargs > 0)
    2565           0 :             scratch->opcode = EEOP_FUNCEXPR_STRICT_FUSAGE;
    2566             :         else
    2567           0 :             scratch->opcode = EEOP_FUNCEXPR_FUSAGE;
    2568             :     }
    2569     1442436 : }
    2570             : 
    2571             : /*
    2572             :  * Add expression steps deforming the ExprState's inner/outer/scan slots
    2573             :  * as much as required by the expression.
    2574             :  */
    2575             : static void
    2576     2272766 : ExecInitExprSlots(ExprState *state, Node *node)
    2577             : {
    2578     2272766 :     LastAttnumInfo info = {0, 0, 0};
    2579             : 
    2580             :     /*
    2581             :      * Figure out which attributes we're going to need.
    2582             :      */
    2583     2272766 :     get_last_attnums_walker(node, &info);
    2584             : 
    2585     2272766 :     ExecPushExprSlots(state, &info);
    2586     2272766 : }
    2587             : 
    2588             : /*
    2589             :  * Add steps deforming the ExprState's inner/out/scan slots as much as
    2590             :  * indicated by info. This is useful when building an ExprState covering more
    2591             :  * than one expression.
    2592             :  */
    2593             : static void
    2594     2342660 : ExecPushExprSlots(ExprState *state, LastAttnumInfo *info)
    2595             : {
    2596     2342660 :     ExprEvalStep scratch = {0};
    2597             : 
    2598     2342660 :     scratch.resvalue = NULL;
    2599     2342660 :     scratch.resnull = NULL;
    2600             : 
    2601             :     /* Emit steps as needed */
    2602     2342660 :     if (info->last_inner > 0)
    2603             :     {
    2604      223148 :         scratch.opcode = EEOP_INNER_FETCHSOME;
    2605      223148 :         scratch.d.fetch.last_var = info->last_inner;
    2606      223148 :         scratch.d.fetch.fixed = false;
    2607      223148 :         scratch.d.fetch.kind = NULL;
    2608      223148 :         scratch.d.fetch.known_desc = NULL;
    2609      223148 :         if (ExecComputeSlotInfo(state, &scratch))
    2610      185088 :             ExprEvalPushStep(state, &scratch);
    2611             :     }
    2612     2342660 :     if (info->last_outer > 0)
    2613             :     {
    2614      477478 :         scratch.opcode = EEOP_OUTER_FETCHSOME;
    2615      477478 :         scratch.d.fetch.last_var = info->last_outer;
    2616      477478 :         scratch.d.fetch.fixed = false;
    2617      477478 :         scratch.d.fetch.kind = NULL;
    2618      477478 :         scratch.d.fetch.known_desc = NULL;
    2619      477478 :         if (ExecComputeSlotInfo(state, &scratch))
    2620      261980 :             ExprEvalPushStep(state, &scratch);
    2621             :     }
    2622     2342660 :     if (info->last_scan > 0)
    2623             :     {
    2624      595858 :         scratch.opcode = EEOP_SCAN_FETCHSOME;
    2625      595858 :         scratch.d.fetch.last_var = info->last_scan;
    2626      595858 :         scratch.d.fetch.fixed = false;
    2627      595858 :         scratch.d.fetch.kind = NULL;
    2628      595858 :         scratch.d.fetch.known_desc = NULL;
    2629      595858 :         if (ExecComputeSlotInfo(state, &scratch))
    2630      580872 :             ExprEvalPushStep(state, &scratch);
    2631             :     }
    2632     2342660 : }
    2633             : 
    2634             : /*
    2635             :  * get_last_attnums_walker: expression walker for ExecInitExprSlots
    2636             :  */
    2637             : static bool
    2638    12323976 : get_last_attnums_walker(Node *node, LastAttnumInfo *info)
    2639             : {
    2640    12323976 :     if (node == NULL)
    2641      391926 :         return false;
    2642    11932050 :     if (IsA(node, Var))
    2643             :     {
    2644     3554462 :         Var        *variable = (Var *) node;
    2645     3554462 :         AttrNumber  attnum = variable->varattno;
    2646             : 
    2647     3554462 :         switch (variable->varno)
    2648             :         {
    2649      661692 :             case INNER_VAR:
    2650      661692 :                 info->last_inner = Max(info->last_inner, attnum);
    2651      661692 :                 break;
    2652             : 
    2653     1646940 :             case OUTER_VAR:
    2654     1646940 :                 info->last_outer = Max(info->last_outer, attnum);
    2655     1646940 :                 break;
    2656             : 
    2657             :                 /* INDEX_VAR is handled by default case */
    2658             : 
    2659     1245830 :             default:
    2660     1245830 :                 info->last_scan = Max(info->last_scan, attnum);
    2661     1245830 :                 break;
    2662             :         }
    2663     3554462 :         return false;
    2664             :     }
    2665             : 
    2666             :     /*
    2667             :      * Don't examine the arguments or filters of Aggrefs or WindowFuncs,
    2668             :      * because those do not represent expressions to be evaluated within the
    2669             :      * calling expression's econtext.  GroupingFunc arguments are never
    2670             :      * evaluated at all.
    2671             :      */
    2672     8377588 :     if (IsA(node, Aggref))
    2673       59516 :         return false;
    2674     8318072 :     if (IsA(node, WindowFunc))
    2675        1512 :         return false;
    2676     8316560 :     if (IsA(node, GroupingFunc))
    2677         192 :         return false;
    2678     8316368 :     return expression_tree_walker(node, get_last_attnums_walker,
    2679             :                                   (void *) info);
    2680             : }
    2681             : 
    2682             : /*
    2683             :  * Compute additional information for EEOP_*_FETCHSOME ops.
    2684             :  *
    2685             :  * The goal is to determine whether a slot is 'fixed', that is, every
    2686             :  * evaluation of the expression will have the same type of slot, with an
    2687             :  * equivalent descriptor.
    2688             :  *
    2689             :  * Returns true if the deforming step is required, false otherwise.
    2690             :  */
    2691             : static bool
    2692     1320124 : ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op)
    2693             : {
    2694     1320124 :     PlanState  *parent = state->parent;
    2695     1320124 :     TupleDesc   desc = NULL;
    2696     1320124 :     const TupleTableSlotOps *tts_ops = NULL;
    2697     1320124 :     bool        isfixed = false;
    2698     1320124 :     ExprEvalOp  opcode = op->opcode;
    2699             : 
    2700             :     Assert(opcode == EEOP_INNER_FETCHSOME ||
    2701             :            opcode == EEOP_OUTER_FETCHSOME ||
    2702             :            opcode == EEOP_SCAN_FETCHSOME);
    2703             : 
    2704     1320124 :     if (op->d.fetch.known_desc != NULL)
    2705             :     {
    2706       23640 :         desc = op->d.fetch.known_desc;
    2707       23640 :         tts_ops = op->d.fetch.kind;
    2708       23640 :         isfixed = op->d.fetch.kind != NULL;
    2709             :     }
    2710     1296484 :     else if (!parent)
    2711             :     {
    2712        7340 :         isfixed = false;
    2713             :     }
    2714     1289144 :     else if (opcode == EEOP_INNER_FETCHSOME)
    2715             :     {
    2716      223092 :         PlanState  *is = innerPlanState(parent);
    2717             : 
    2718      223092 :         if (parent->inneropsset && !parent->inneropsfixed)
    2719             :         {
    2720           0 :             isfixed = false;
    2721             :         }
    2722      223092 :         else if (parent->inneropsset && parent->innerops)
    2723             :         {
    2724           0 :             isfixed = true;
    2725           0 :             tts_ops = parent->innerops;
    2726           0 :             desc = ExecGetResultType(is);
    2727             :         }
    2728      223092 :         else if (is)
    2729             :         {
    2730      222584 :             tts_ops = ExecGetResultSlotOps(is, &isfixed);
    2731      222584 :             desc = ExecGetResultType(is);
    2732             :         }
    2733             :     }
    2734     1066052 :     else if (opcode == EEOP_OUTER_FETCHSOME)
    2735             :     {
    2736      477354 :         PlanState  *os = outerPlanState(parent);
    2737             : 
    2738      477354 :         if (parent->outeropsset && !parent->outeropsfixed)
    2739             :         {
    2740        3180 :             isfixed = false;
    2741             :         }
    2742      474174 :         else if (parent->outeropsset && parent->outerops)
    2743             :         {
    2744       52772 :             isfixed = true;
    2745       52772 :             tts_ops = parent->outerops;
    2746       52772 :             desc = ExecGetResultType(os);
    2747             :         }
    2748      421402 :         else if (os)
    2749             :         {
    2750      421402 :             tts_ops = ExecGetResultSlotOps(os, &isfixed);
    2751      421402 :             desc = ExecGetResultType(os);
    2752             :         }
    2753             :     }
    2754      588698 :     else if (opcode == EEOP_SCAN_FETCHSOME)
    2755             :     {
    2756      588698 :         desc = parent->scandesc;
    2757             : 
    2758      588698 :         if (parent->scanops)
    2759      573424 :             tts_ops = parent->scanops;
    2760             : 
    2761      588698 :         if (parent->scanopsset)
    2762      573424 :             isfixed = parent->scanopsfixed;
    2763             :     }
    2764             : 
    2765     1320124 :     if (isfixed && desc != NULL && tts_ops != NULL)
    2766             :     {
    2767     1280442 :         op->d.fetch.fixed = true;
    2768     1280442 :         op->d.fetch.kind = tts_ops;
    2769     1280442 :         op->d.fetch.known_desc = desc;
    2770             :     }
    2771             :     else
    2772             :     {
    2773       39682 :         op->d.fetch.fixed = false;
    2774       39682 :         op->d.fetch.kind = NULL;
    2775       39682 :         op->d.fetch.known_desc = NULL;
    2776             :     }
    2777             : 
    2778             :     /* if the slot is known to always virtual we never need to deform */
    2779     1320124 :     if (op->d.fetch.fixed && op->d.fetch.kind == &TTSOpsVirtual)
    2780      270792 :         return false;
    2781             : 
    2782     1049332 :     return true;
    2783             : }
    2784             : 
    2785             : /*
    2786             :  * Prepare step for the evaluation of a whole-row variable.
    2787             :  * The caller still has to push the step.
    2788             :  */
    2789             : static void
    2790        2470 : ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state)
    2791             : {
    2792        2470 :     PlanState  *parent = state->parent;
    2793             : 
    2794             :     /* fill in all but the target */
    2795        2470 :     scratch->opcode = EEOP_WHOLEROW;
    2796        2470 :     scratch->d.wholerow.var = variable;
    2797        2470 :     scratch->d.wholerow.first = true;
    2798        2470 :     scratch->d.wholerow.slow = false;
    2799        2470 :     scratch->d.wholerow.tupdesc = NULL; /* filled at runtime */
    2800        2470 :     scratch->d.wholerow.junkFilter = NULL;
    2801             : 
    2802             :     /*
    2803             :      * If the input tuple came from a subquery, it might contain "resjunk"
    2804             :      * columns (such as GROUP BY or ORDER BY columns), which we don't want to
    2805             :      * keep in the whole-row result.  We can get rid of such columns by
    2806             :      * passing the tuple through a JunkFilter --- but to make one, we have to
    2807             :      * lay our hands on the subquery's targetlist.  Fortunately, there are not
    2808             :      * very many cases where this can happen, and we can identify all of them
    2809             :      * by examining our parent PlanState.  We assume this is not an issue in
    2810             :      * standalone expressions that don't have parent plans.  (Whole-row Vars
    2811             :      * can occur in such expressions, but they will always be referencing
    2812             :      * table rows.)
    2813             :      */
    2814        2470 :     if (parent)
    2815             :     {
    2816        2448 :         PlanState  *subplan = NULL;
    2817             : 
    2818        2448 :         switch (nodeTag(parent))
    2819             :         {
    2820         166 :             case T_SubqueryScanState:
    2821         166 :                 subplan = ((SubqueryScanState *) parent)->subplan;
    2822         166 :                 break;
    2823         100 :             case T_CteScanState:
    2824         100 :                 subplan = ((CteScanState *) parent)->cteplanstate;
    2825         100 :                 break;
    2826        2182 :             default:
    2827        2182 :                 break;
    2828             :         }
    2829             : 
    2830        2448 :         if (subplan)
    2831             :         {
    2832         266 :             bool        junk_filter_needed = false;
    2833             :             ListCell   *tlist;
    2834             : 
    2835             :             /* Detect whether subplan tlist actually has any junk columns */
    2836         718 :             foreach(tlist, subplan->plan->targetlist)
    2837             :             {
    2838         460 :                 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
    2839             : 
    2840         460 :                 if (tle->resjunk)
    2841             :                 {
    2842           8 :                     junk_filter_needed = true;
    2843           8 :                     break;
    2844             :                 }
    2845             :             }
    2846             : 
    2847             :             /* If so, build the junkfilter now */
    2848         266 :             if (junk_filter_needed)
    2849             :             {
    2850           8 :                 scratch->d.wholerow.junkFilter =
    2851           8 :                     ExecInitJunkFilter(subplan->plan->targetlist,
    2852             :                                        ExecInitExtraTupleSlot(parent->state, NULL,
    2853             :                                                               &TTSOpsVirtual));
    2854             :             }
    2855             :         }
    2856             :     }
    2857        2470 : }
    2858             : 
    2859             : /*
    2860             :  * Prepare evaluation of a SubscriptingRef expression.
    2861             :  */
    2862             : static void
    2863        9762 : ExecInitSubscriptingRef(ExprEvalStep *scratch, SubscriptingRef *sbsref,
    2864             :                         ExprState *state, Datum *resv, bool *resnull)
    2865             : {
    2866        9762 :     bool        isAssignment = (sbsref->refassgnexpr != NULL);
    2867        9762 :     int         nupper = list_length(sbsref->refupperindexpr);
    2868        9762 :     int         nlower = list_length(sbsref->reflowerindexpr);
    2869             :     const SubscriptRoutines *sbsroutines;
    2870             :     SubscriptingRefState *sbsrefstate;
    2871             :     SubscriptExecSteps methods;
    2872             :     char       *ptr;
    2873        9762 :     List       *adjust_jumps = NIL;
    2874             :     ListCell   *lc;
    2875             :     int         i;
    2876             : 
    2877             :     /* Look up the subscripting support methods */
    2878        9762 :     sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
    2879        9762 :     if (!sbsroutines)
    2880           0 :         ereport(ERROR,
    2881             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2882             :                  errmsg("cannot subscript type %s because it does not support subscripting",
    2883             :                         format_type_be(sbsref->refcontainertype)),
    2884             :                  state->parent ?
    2885             :                  executor_errposition(state->parent->state,
    2886             :                                       exprLocation((Node *) sbsref)) : 0));
    2887             : 
    2888             :     /* Allocate sbsrefstate, with enough space for per-subscript arrays too */
    2889        9762 :     sbsrefstate = palloc0(MAXALIGN(sizeof(SubscriptingRefState)) +
    2890        9762 :                           (nupper + nlower) * (sizeof(Datum) +
    2891             :                                                2 * sizeof(bool)));
    2892             : 
    2893             :     /* Fill constant fields of SubscriptingRefState */
    2894        9762 :     sbsrefstate->isassignment = isAssignment;
    2895        9762 :     sbsrefstate->numupper = nupper;
    2896        9762 :     sbsrefstate->numlower = nlower;
    2897             :     /* Set up per-subscript arrays */
    2898        9762 :     ptr = ((char *) sbsrefstate) + MAXALIGN(sizeof(SubscriptingRefState));
    2899        9762 :     sbsrefstate->upperindex = (Datum *) ptr;
    2900        9762 :     ptr += nupper * sizeof(Datum);
    2901        9762 :     sbsrefstate->lowerindex = (Datum *) ptr;
    2902        9762 :     ptr += nlower * sizeof(Datum);
    2903        9762 :     sbsrefstate->upperprovided = (bool *) ptr;
    2904        9762 :     ptr += nupper * sizeof(bool);
    2905        9762 :     sbsrefstate->lowerprovided = (bool *) ptr;
    2906        9762 :     ptr += nlower * sizeof(bool);
    2907        9762 :     sbsrefstate->upperindexnull = (bool *) ptr;
    2908        9762 :     ptr += nupper * sizeof(bool);
    2909        9762 :     sbsrefstate->lowerindexnull = (bool *) ptr;
    2910             :     /* ptr += nlower * sizeof(bool); */
    2911             : 
    2912             :     /*
    2913             :      * Let the container-type-specific code have a chance.  It must fill the
    2914             :      * "methods" struct with function pointers for us to possibly use in
    2915             :      * execution steps below; and it can optionally set up some data pointed
    2916             :      * to by the workspace field.
    2917             :      */
    2918        9762 :     memset(&methods, 0, sizeof(methods));
    2919        9762 :     sbsroutines->exec_setup(sbsref, sbsrefstate, &methods);
    2920             : 
    2921             :     /*
    2922             :      * Evaluate array input.  It's safe to do so into resv/resnull, because we
    2923             :      * won't use that as target for any of the other subexpressions, and it'll
    2924             :      * be overwritten by the final EEOP_SBSREF_FETCH/ASSIGN step, which is
    2925             :      * pushed last.
    2926             :      */
    2927        9762 :     ExecInitExprRec(sbsref->refexpr, state, resv, resnull);
    2928             : 
    2929             :     /*
    2930             :      * If refexpr yields NULL, and the operation should be strict, then result
    2931             :      * is NULL.  We can implement this with just JUMP_IF_NULL, since we
    2932             :      * evaluated the array into the desired target location.
    2933             :      */
    2934        9762 :     if (!isAssignment && sbsroutines->fetch_strict)
    2935             :     {
    2936        9032 :         scratch->opcode = EEOP_JUMP_IF_NULL;
    2937        9032 :         scratch->d.jump.jumpdone = -1;   /* adjust later */
    2938        9032 :         ExprEvalPushStep(state, scratch);
    2939        9032 :         adjust_jumps = lappend_int(adjust_jumps,
    2940        9032 :                                    state->steps_len - 1);
    2941             :     }
    2942             : 
    2943             :     /* Evaluate upper subscripts */
    2944        9762 :     i = 0;
    2945       19914 :     foreach(lc, sbsref->refupperindexpr)
    2946             :     {
    2947       10152 :         Expr       *e = (Expr *) lfirst(lc);
    2948             : 
    2949             :         /* When slicing, individual subscript bounds can be omitted */
    2950       10152 :         if (!e)
    2951             :         {
    2952          52 :             sbsrefstate->upperprovided[i] = false;
    2953          52 :             sbsrefstate->upperindexnull[i] = true;
    2954             :         }
    2955             :         else
    2956             :         {
    2957       10100 :             sbsrefstate->upperprovided[i] = true;
    2958             :             /* Each subscript is evaluated into appropriate array entry */
    2959       10100 :             ExecInitExprRec(e, state,
    2960       10100 :                             &sbsrefstate->upperindex[i],
    2961       10100 :                             &sbsrefstate->upperindexnull[i]);
    2962             :         }
    2963       10152 :         i++;
    2964             :     }
    2965             : 
    2966             :     /* Evaluate lower subscripts similarly */
    2967        9762 :     i = 0;
    2968       10136 :     foreach(lc, sbsref->reflowerindexpr)
    2969             :     {
    2970         374 :         Expr       *e = (Expr *) lfirst(lc);
    2971             : 
    2972             :         /* When slicing, individual subscript bounds can be omitted */
    2973         374 :         if (!e)
    2974             :         {
    2975          52 :             sbsrefstate->lowerprovided[i] = false;
    2976          52 :             sbsrefstate->lowerindexnull[i] = true;
    2977             :         }
    2978             :         else
    2979             :         {
    2980         322 :             sbsrefstate->lowerprovided[i] = true;
    2981             :             /* Each subscript is evaluated into appropriate array entry */
    2982         322 :             ExecInitExprRec(e, state,
    2983         322 :                             &sbsrefstate->lowerindex[i],
    2984         322 :                             &sbsrefstate->lowerindexnull[i]);
    2985             :         }
    2986         374 :         i++;
    2987             :     }
    2988             : 
    2989             :     /* SBSREF_SUBSCRIPTS checks and converts all the subscripts at once */
    2990        9762 :     if (methods.sbs_check_subscripts)
    2991             :     {
    2992        9748 :         scratch->opcode = EEOP_SBSREF_SUBSCRIPTS;
    2993        9748 :         scratch->d.sbsref_subscript.subscriptfunc = methods.sbs_check_subscripts;
    2994        9748 :         scratch->d.sbsref_subscript.state = sbsrefstate;
    2995        9748 :         scratch->d.sbsref_subscript.jumpdone = -1;   /* adjust later */
    2996        9748 :         ExprEvalPushStep(state, scratch);
    2997        9748 :         adjust_jumps = lappend_int(adjust_jumps,
    2998        9748 :                                    state->steps_len - 1);
    2999             :     }
    3000             : 
    3001        9762 :     if (isAssignment)
    3002             :     {
    3003             :         Datum      *save_innermost_caseval;
    3004             :         bool       *save_innermost_casenull;
    3005             : 
    3006             :         /* Check for unimplemented methods */
    3007         730 :         if (!methods.sbs_assign)
    3008           0 :             ereport(ERROR,
    3009             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3010             :                      errmsg("type %s does not support subscripted assignment",
    3011             :                             format_type_be(sbsref->refcontainertype))));
    3012             : 
    3013             :         /*
    3014             :          * We might have a nested-assignment situation, in which the
    3015             :          * refassgnexpr is itself a FieldStore or SubscriptingRef that needs
    3016             :          * to obtain and modify the previous value of the array element or
    3017             :          * slice being replaced.  If so, we have to extract that value from
    3018             :          * the array and pass it down via the CaseTestExpr mechanism.  It's
    3019             :          * safe to reuse the CASE mechanism because there cannot be a CASE
    3020             :          * between here and where the value would be needed, and an array
    3021             :          * assignment can't be within a CASE either.  (So saving and restoring
    3022             :          * innermost_caseval is just paranoia, but let's do it anyway.)
    3023             :          *
    3024             :          * Since fetching the old element might be a nontrivial expense, do it
    3025             :          * only if the argument actually needs it.
    3026             :          */
    3027         730 :         if (isAssignmentIndirectionExpr(sbsref->refassgnexpr))
    3028             :         {
    3029          98 :             if (!methods.sbs_fetch_old)
    3030           0 :                 ereport(ERROR,
    3031             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3032             :                          errmsg("type %s does not support subscripted assignment",
    3033             :                                 format_type_be(sbsref->refcontainertype))));
    3034          98 :             scratch->opcode = EEOP_SBSREF_OLD;
    3035          98 :             scratch->d.sbsref.subscriptfunc = methods.sbs_fetch_old;
    3036          98 :             scratch->d.sbsref.state = sbsrefstate;
    3037          98 :             ExprEvalPushStep(state, scratch);
    3038             :         }
    3039             : 
    3040             :         /* SBSREF_OLD puts extracted value into prevvalue/prevnull */
    3041         730 :         save_innermost_caseval = state->innermost_caseval;
    3042         730 :         save_innermost_casenull = state->innermost_casenull;
    3043         730 :         state->innermost_caseval = &sbsrefstate->prevvalue;
    3044         730 :         state->innermost_casenull = &sbsrefstate->prevnull;
    3045             : 
    3046             :         /* evaluate replacement value into replacevalue/replacenull */
    3047         730 :         ExecInitExprRec(sbsref->refassgnexpr, state,
    3048             :                         &sbsrefstate->replacevalue, &sbsrefstate->replacenull);
    3049             : 
    3050         730 :         state->innermost_caseval = save_innermost_caseval;
    3051         730 :         state->innermost_casenull = save_innermost_casenull;
    3052             : 
    3053             :         /* and perform the assignment */
    3054         730 :         scratch->opcode = EEOP_SBSREF_ASSIGN;
    3055         730 :         scratch->d.sbsref.subscriptfunc = methods.sbs_assign;
    3056         730 :         scratch->d.sbsref.state = sbsrefstate;
    3057         730 :         ExprEvalPushStep(state, scratch);
    3058             :     }
    3059             :     else
    3060             :     {
    3061             :         /* array fetch is much simpler */
    3062        9032 :         scratch->opcode = EEOP_SBSREF_FETCH;
    3063        9032 :         scratch->d.sbsref.subscriptfunc = methods.sbs_fetch;
    3064        9032 :         scratch->d.sbsref.state = sbsrefstate;
    3065        9032 :         ExprEvalPushStep(state, scratch);
    3066             :     }
    3067             : 
    3068             :     /* adjust jump targets */
    3069       28542 :     foreach(lc, adjust_jumps)
    3070             :     {
    3071       18780 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    3072             : 
    3073       18780 :         if (as->opcode == EEOP_SBSREF_SUBSCRIPTS)
    3074             :         {
    3075             :             Assert(as->d.sbsref_subscript.jumpdone == -1);
    3076        9748 :             as->d.sbsref_subscript.jumpdone = state->steps_len;
    3077             :         }
    3078             :         else
    3079             :         {
    3080             :             Assert(as->opcode == EEOP_JUMP_IF_NULL);
    3081             :             Assert(as->d.jump.jumpdone == -1);
    3082        9032 :             as->d.jump.jumpdone = state->steps_len;
    3083             :         }
    3084             :     }
    3085        9762 : }
    3086             : 
    3087             : /*
    3088             :  * Helper for preparing SubscriptingRef expressions for evaluation: is expr
    3089             :  * a nested FieldStore or SubscriptingRef that needs the old element value
    3090             :  * passed down?
    3091             :  *
    3092             :  * (We could use this in FieldStore too, but in that case passing the old
    3093             :  * value is so cheap there's no need.)
    3094             :  *
    3095             :  * Note: it might seem that this needs to recurse, but in most cases it does
    3096             :  * not; the CaseTestExpr, if any, will be directly the arg or refexpr of the
    3097             :  * top-level node.  Nested-assignment situations give rise to expression
    3098             :  * trees in which each level of assignment has its own CaseTestExpr, and the
    3099             :  * recursive structure appears within the newvals or refassgnexpr field.
    3100             :  * There is an exception, though: if the array is an array-of-domain, we will
    3101             :  * have a CoerceToDomain as the refassgnexpr, and we need to be able to look
    3102             :  * through that.
    3103             :  */
    3104             : static bool
    3105         750 : isAssignmentIndirectionExpr(Expr *expr)
    3106             : {
    3107         750 :     if (expr == NULL)
    3108           0 :         return false;           /* just paranoia */
    3109         750 :     if (IsA(expr, FieldStore))
    3110             :     {
    3111          98 :         FieldStore *fstore = (FieldStore *) expr;
    3112             : 
    3113          98 :         if (fstore->arg && IsA(fstore->arg, CaseTestExpr))
    3114          98 :             return true;
    3115             :     }
    3116         652 :     else if (IsA(expr, SubscriptingRef))
    3117             :     {
    3118          22 :         SubscriptingRef *sbsRef = (SubscriptingRef *) expr;
    3119             : 
    3120          22 :         if (sbsRef->refexpr && IsA(sbsRef->refexpr, CaseTestExpr))
    3121           0 :             return true;
    3122             :     }
    3123         630 :     else if (IsA(expr, CoerceToDomain))
    3124             :     {
    3125          20 :         CoerceToDomain *cd = (CoerceToDomain *) expr;
    3126             : 
    3127          20 :         return isAssignmentIndirectionExpr(cd->arg);
    3128             :     }
    3129         632 :     return false;
    3130             : }
    3131             : 
    3132             : /*
    3133             :  * Prepare evaluation of a CoerceToDomain expression.
    3134             :  */
    3135             : static void
    3136       35140 : ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
    3137             :                        ExprState *state, Datum *resv, bool *resnull)
    3138             : {
    3139             :     DomainConstraintRef *constraint_ref;
    3140       35140 :     Datum      *domainval = NULL;
    3141       35140 :     bool       *domainnull = NULL;
    3142             :     ListCell   *l;
    3143             : 
    3144       35140 :     scratch->d.domaincheck.resulttype = ctest->resulttype;
    3145             :     /* we'll allocate workspace only if needed */
    3146       35140 :     scratch->d.domaincheck.checkvalue = NULL;
    3147       35140 :     scratch->d.domaincheck.checknull = NULL;
    3148             : 
    3149             :     /*
    3150             :      * Evaluate argument - it's fine to directly store it into resv/resnull,
    3151             :      * if there's constraint failures there'll be errors, otherwise it's what
    3152             :      * needs to be returned.
    3153             :      */
    3154       35140 :     ExecInitExprRec(ctest->arg, state, resv, resnull);
    3155             : 
    3156             :     /*
    3157             :      * Note: if the argument is of varlena type, it could be a R/W expanded
    3158             :      * object.  We want to return the R/W pointer as the final result, but we
    3159             :      * have to pass a R/O pointer as the value to be tested by any functions
    3160             :      * in check expressions.  We don't bother to emit a MAKE_READONLY step
    3161             :      * unless there's actually at least one check expression, though.  Until
    3162             :      * we've tested that, domainval/domainnull are NULL.
    3163             :      */
    3164             : 
    3165             :     /*
    3166             :      * Collect the constraints associated with the domain.
    3167             :      *
    3168             :      * Note: before PG v10 we'd recheck the set of constraints during each
    3169             :      * evaluation of the expression.  Now we bake them into the ExprState
    3170             :      * during executor initialization.  That means we don't need typcache.c to
    3171             :      * provide compiled exprs.
    3172             :      */
    3173             :     constraint_ref = (DomainConstraintRef *)
    3174       35140 :         palloc(sizeof(DomainConstraintRef));
    3175       35140 :     InitDomainConstraintRef(ctest->resulttype,
    3176             :                             constraint_ref,
    3177             :                             CurrentMemoryContext,
    3178             :                             false);
    3179             : 
    3180             :     /*
    3181             :      * Compile code to check each domain constraint.  NOTNULL constraints can
    3182             :      * just be applied on the resv/resnull value, but for CHECK constraints we
    3183             :      * need more pushups.
    3184             :      */
    3185       71176 :     foreach(l, constraint_ref->constraints)
    3186             :     {
    3187       36036 :         DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
    3188             :         Datum      *save_innermost_domainval;
    3189             :         bool       *save_innermost_domainnull;
    3190             : 
    3191       36036 :         scratch->d.domaincheck.constraintname = con->name;
    3192             : 
    3193       36036 :         switch (con->constrainttype)
    3194             :         {
    3195         264 :             case DOM_CONSTRAINT_NOTNULL:
    3196         264 :                 scratch->opcode = EEOP_DOMAIN_NOTNULL;
    3197         264 :                 ExprEvalPushStep(state, scratch);
    3198         264 :                 break;
    3199       35772 :             case DOM_CONSTRAINT_CHECK:
    3200             :                 /* Allocate workspace for CHECK output if we didn't yet */
    3201       35772 :                 if (scratch->d.domaincheck.checkvalue == NULL)
    3202             :                 {
    3203       34944 :                     scratch->d.domaincheck.checkvalue =
    3204       34944 :                         (Datum *) palloc(sizeof(Datum));
    3205       34944 :                     scratch->d.domaincheck.checknull =
    3206       34944 :                         (bool *) palloc(sizeof(bool));
    3207             :                 }
    3208             : 
    3209             :                 /*
    3210             :                  * If first time through, determine where CoerceToDomainValue
    3211             :                  * nodes should read from.
    3212             :                  */
    3213       35772 :                 if (domainval == NULL)
    3214             :                 {
    3215             :                     /*
    3216             :                      * Since value might be read multiple times, force to R/O
    3217             :                      * - but only if it could be an expanded datum.
    3218             :                      */
    3219       34944 :                     if (get_typlen(ctest->resulttype) == -1)
    3220             :                     {
    3221        6106 :                         ExprEvalStep scratch2 = {0};
    3222             : 
    3223             :                         /* Yes, so make output workspace for MAKE_READONLY */
    3224        6106 :                         domainval = (Datum *) palloc(sizeof(Datum));
    3225        6106 :                         domainnull = (bool *) palloc(sizeof(bool));
    3226             : 
    3227             :                         /* Emit MAKE_READONLY */
    3228        6106 :                         scratch2.opcode = EEOP_MAKE_READONLY;
    3229        6106 :                         scratch2.resvalue = domainval;
    3230        6106 :                         scratch2.resnull = domainnull;
    3231        6106 :                         scratch2.d.make_readonly.value = resv;
    3232        6106 :                         scratch2.d.make_readonly.isnull = resnull;
    3233        6106 :                         ExprEvalPushStep(state, &scratch2);
    3234             :                     }
    3235             :                     else
    3236             :                     {
    3237             :                         /* No, so it's fine to read from resv/resnull */
    3238       28838 :                         domainval = resv;
    3239       28838 :                         domainnull = resnull;
    3240             :                     }
    3241             :                 }
    3242             : 
    3243             :                 /*
    3244             :                  * Set up value to be returned by CoerceToDomainValue nodes.
    3245             :                  * We must save and restore innermost_domainval/null fields,
    3246             :                  * in case this node is itself within a check expression for
    3247             :                  * another domain.
    3248             :                  */
    3249       35772 :                 save_innermost_domainval = state->innermost_domainval;
    3250       35772 :                 save_innermost_domainnull = state->innermost_domainnull;
    3251       35772 :                 state->innermost_domainval = domainval;
    3252       35772 :                 state->innermost_domainnull = domainnull;
    3253             : 
    3254             :                 /* evaluate check expression value */
    3255       35772 :                 ExecInitExprRec(con->check_expr, state,
    3256             :                                 scratch->d.domaincheck.checkvalue,
    3257             :                                 scratch->d.domaincheck.checknull);
    3258             : 
    3259       35772 :                 state->innermost_domainval = save_innermost_domainval;
    3260       35772 :                 state->innermost_domainnull = save_innermost_domainnull;
    3261             : 
    3262             :                 /* now test result */
    3263       35772 :                 scratch->opcode = EEOP_DOMAIN_CHECK;
    3264       35772 :                 ExprEvalPushStep(state, scratch);
    3265             : 
    3266       35772 :                 break;
    3267           0 :             default:
    3268           0 :                 elog(ERROR, "unrecognized constraint type: %d",
    3269             :                      (int) con->constrainttype);
    3270             :                 break;
    3271             :         }
    3272             :     }
    3273       35140 : }
    3274             : 
    3275             : /*
    3276             :  * Build transition/combine function invocations for all aggregate transition
    3277             :  * / combination function invocations in a grouping sets phase. This has to
    3278             :  * invoke all sort based transitions in a phase (if doSort is true), all hash
    3279             :  * based transitions (if doHash is true), or both (both true).
    3280             :  *
    3281             :  * The resulting expression will, for each set of transition values, first
    3282             :  * check for filters, evaluate aggregate input, check that that input is not
    3283             :  * NULL for a strict transition function, and then finally invoke the
    3284             :  * transition for each of the concurrently computed grouping sets.
    3285             :  *
    3286             :  * If nullcheck is true, the generated code will check for a NULL pointer to
    3287             :  * the array of AggStatePerGroup, and skip evaluation if so.
    3288             :  */
    3289             : ExprState *
    3290       58234 : ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase,
    3291             :                   bool doSort, bool doHash, bool nullcheck)
    3292             : {
    3293       58234 :     ExprState  *state = makeNode(ExprState);
    3294       58234 :     PlanState  *parent = &aggstate->ss.ps;
    3295       58234 :     ExprEvalStep scratch = {0};
    3296       58234 :     bool        isCombine = DO_AGGSPLIT_COMBINE(aggstate->aggsplit);
    3297       58234 :     LastAttnumInfo deform = {0, 0, 0};
    3298             : 
    3299       58234 :     state->expr = (Expr *) aggstate;
    3300       58234 :     state->parent = parent;
    3301             : 
    3302       58234 :     scratch.resvalue = &state->resvalue;
    3303       58234 :     scratch.resnull = &state->resnull;
    3304             : 
    3305             :     /*
    3306             :      * First figure out which slots, and how many columns from each, we're
    3307             :      * going to need.
    3308             :      */
    3309      117622 :     for (int transno = 0; transno < aggstate->numtrans; transno++)
    3310             :     {
    3311       59388 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    3312             : 
    3313       59388 :         get_last_attnums_walker((Node *) pertrans->aggref->aggdirectargs,
    3314             :                                 &deform);
    3315       59388 :         get_last_attnums_walker((Node *) pertrans->aggref->args,
    3316             :                                 &deform);
    3317       59388 :         get_last_attnums_walker((Node *) pertrans->aggref->aggorder,
    3318             :                                 &deform);
    3319       59388 :         get_last_attnums_walker((Node *) pertrans->aggref->aggdistinct,
    3320             :                                 &deform);
    3321       59388 :         get_last_attnums_walker((Node *) pertrans->aggref->aggfilter,
    3322             :                                 &deform);
    3323             :     }
    3324       58234 :     ExecPushExprSlots(state, &deform);
    3325             : 
    3326             :     /*
    3327             :      * Emit instructions for each transition value / grouping set combination.
    3328             :      */
    3329      117622 :     for (int transno = 0; transno < aggstate->numtrans; transno++)
    3330             :     {
    3331       59388 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    3332       59388 :         FunctionCallInfo trans_fcinfo = pertrans->transfn_fcinfo;
    3333       59388 :         List       *adjust_bailout = NIL;
    3334       59388 :         NullableDatum *strictargs = NULL;
    3335       59388 :         bool       *strictnulls = NULL;
    3336             :         int         argno;
    3337             :         ListCell   *bail;
    3338             : 
    3339             :         /*
    3340             :          * If filter present, emit. Do so before evaluating the input, to
    3341             :          * avoid potentially unneeded computations, or even worse, unintended
    3342             :          * side-effects.  When combining, all the necessary filtering has
    3343             :          * already been done.
    3344             :          */
    3345       59388 :         if (pertrans->aggref->aggfilter && !isCombine)
    3346             :         {
    3347             :             /* evaluate filter expression */
    3348         518 :             ExecInitExprRec(pertrans->aggref->aggfilter, state,
    3349             :                             &state->resvalue, &state->resnull);
    3350             :             /* and jump out if false */
    3351         518 :             scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    3352         518 :             scratch.d.jump.jumpdone = -1;   /* adjust later */
    3353         518 :             ExprEvalPushStep(state, &scratch);
    3354         518 :             adjust_bailout = lappend_int(adjust_bailout,
    3355         518 :                                          state->steps_len - 1);
    3356             :         }
    3357             : 
    3358             :         /*
    3359             :          * Evaluate arguments to aggregate/combine function.
    3360             :          */
    3361       59388 :         argno = 0;
    3362       59388 :         if (isCombine)
    3363             :         {
    3364             :             /*
    3365             :              * Combining two aggregate transition values. Instead of directly
    3366             :              * coming from a tuple the input is a, potentially deserialized,
    3367             :              * transition value.
    3368             :              */
    3369             :             TargetEntry *source_tle;
    3370             : 
    3371             :             Assert(pertrans->numSortCols == 0);
    3372             :             Assert(list_length(pertrans->aggref->args) == 1);
    3373             : 
    3374         840 :             strictargs = trans_fcinfo->args + 1;
    3375         840 :             source_tle = (TargetEntry *) linitial(pertrans->aggref->args);
    3376             : 
    3377             :             /*
    3378             :              * deserialfn_oid will be set if we must deserialize the input
    3379             :              * state before calling the combine function.
    3380             :              */
    3381         840 :             if (!OidIsValid(pertrans->deserialfn_oid))
    3382             :             {
    3383             :                 /*
    3384             :                  * Start from 1, since the 0th arg will be the transition
    3385             :                  * value
    3386             :                  */
    3387         792 :                 ExecInitExprRec(source_tle->expr, state,
    3388         792 :                                 &trans_fcinfo->args[argno + 1].value,
    3389         792 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3390             :             }
    3391             :             else
    3392             :             {
    3393          48 :                 FunctionCallInfo ds_fcinfo = pertrans->deserialfn_fcinfo;
    3394             : 
    3395             :                 /* evaluate argument */
    3396          48 :                 ExecInitExprRec(source_tle->expr, state,
    3397             :                                 &ds_fcinfo->args[0].value,
    3398             :                                 &ds_fcinfo->args[0].isnull);
    3399             : 
    3400             :                 /* Dummy second argument for type-safety reasons */
    3401          48 :                 ds_fcinfo->args[1].value = PointerGetDatum(NULL);
    3402          48 :                 ds_fcinfo->args[1].isnull = false;
    3403             : 
    3404             :                 /*
    3405             :                  * Don't call a strict deserialization function with NULL
    3406             :                  * input
    3407             :                  */
    3408          48 :                 if (pertrans->deserialfn.fn_strict)
    3409          48 :                     scratch.opcode = EEOP_AGG_STRICT_DESERIALIZE;
    3410             :                 else
    3411           0 :                     scratch.opcode = EEOP_AGG_DESERIALIZE;
    3412             : 
    3413          48 :                 scratch.d.agg_deserialize.fcinfo_data = ds_fcinfo;
    3414          48 :                 scratch.d.agg_deserialize.jumpnull = -1;    /* adjust later */
    3415          48 :                 scratch.resvalue = &trans_fcinfo->args[argno + 1].value;
    3416          48 :                 scratch.resnull = &trans_fcinfo->args[argno + 1].isnull;
    3417             : 
    3418          48 :                 ExprEvalPushStep(state, &scratch);
    3419             :                 /* don't add an adjustment unless the function is strict */
    3420          48 :                 if (pertrans->deserialfn.fn_strict)
    3421          48 :                     adjust_bailout = lappend_int(adjust_bailout,
    3422          48 :                                                  state->steps_len - 1);
    3423             : 
    3424             :                 /* restore normal settings of scratch fields */
    3425          48 :                 scratch.resvalue = &state->resvalue;
    3426          48 :                 scratch.resnull = &state->resnull;
    3427             :             }
    3428         840 :             argno++;
    3429             :         }
    3430       58548 :         else if (pertrans->numSortCols == 0)
    3431             :         {
    3432             :             ListCell   *arg;
    3433             : 
    3434             :             /*
    3435             :              * Normal transition function without ORDER BY / DISTINCT.
    3436             :              */
    3437       26628 :             strictargs = trans_fcinfo->args + 1;
    3438             : 
    3439       44696 :             foreach(arg, pertrans->aggref->args)
    3440             :             {
    3441       18068 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3442             : 
    3443             :                 /*
    3444             :                  * Start from 1, since the 0th arg will be the transition
    3445             :                  * value
    3446             :                  */
    3447       18068 :                 ExecInitExprRec(source_tle->expr, state,
    3448       18068 :                                 &trans_fcinfo->args[argno + 1].value,
    3449       18068 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3450       18068 :                 argno++;
    3451             :             }
    3452             :         }
    3453       31920 :         else if (pertrans->numInputs == 1)
    3454             :         {
    3455             :             /*
    3456             :              * DISTINCT and/or ORDER BY case, with a single column sorted on.
    3457             :              */
    3458       12352 :             TargetEntry *source_tle =
    3459       12352 :             (TargetEntry *) linitial(pertrans->aggref->args);
    3460             : 
    3461             :             Assert(list_length(pertrans->aggref->args) == 1);
    3462             : 
    3463       12352 :             ExecInitExprRec(source_tle->expr, state,
    3464             :                             &state->resvalue,
    3465             :                             &state->resnull);
    3466       12352 :             strictnulls = &state->resnull;
    3467       12352 :             argno++;
    3468             :         }
    3469             :         else
    3470             :         {
    3471             :             /*
    3472             :              * DISTINCT and/or ORDER BY case, with multiple columns sorted on.
    3473             :              */
    3474       19568 :             Datum      *values = pertrans->sortslot->tts_values;
    3475       19568 :             bool       *nulls = pertrans->sortslot->tts_isnull;
    3476             :             ListCell   *arg;
    3477             : 
    3478       19568 :             strictnulls = nulls;
    3479             : 
    3480       59108 :             foreach(arg, pertrans->aggref->args)
    3481             :             {
    3482       39540 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3483             : 
    3484       39540 :                 ExecInitExprRec(source_tle->expr, state,
    3485       39540 :                                 &values[argno], &nulls[argno]);
    3486       39540 :                 argno++;
    3487             :             }
    3488             :         }
    3489             :         Assert(pertrans->numInputs == argno);
    3490             : 
    3491             :         /*
    3492             :          * For a strict transfn, nothing happens when there's a NULL input; we
    3493             :          * just keep the prior transValue. This is true for both plain and
    3494             :          * sorted/distinct aggregates.
    3495             :          */
    3496       59388 :         if (trans_fcinfo->flinfo->fn_strict && pertrans->numTransInputs > 0)
    3497             :         {
    3498        7372 :             if (strictnulls)
    3499         126 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_NULLS;
    3500             :             else
    3501        7246 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_ARGS;
    3502        7372 :             scratch.d.agg_strict_input_check.nulls = strictnulls;
    3503        7372 :             scratch.d.agg_strict_input_check.args = strictargs;
    3504        7372 :             scratch.d.agg_strict_input_check.jumpnull = -1; /* adjust later */
    3505        7372 :             scratch.d.agg_strict_input_check.nargs = pertrans->numTransInputs;
    3506        7372 :             ExprEvalPushStep(state, &scratch);
    3507        7372 :             adjust_bailout = lappend_int(adjust_bailout,
    3508        7372 :                                          state->steps_len - 1);
    3509             :         }
    3510             : 
    3511             :         /*
    3512             :          * Call transition function (once for each concurrently evaluated
    3513             :          * grouping set). Do so for both sort and hash based computations, as
    3514             :          * applicable.
    3515             :          */
    3516       59388 :         if (doSort)
    3517             :         {
    3518       55396 :             int         processGroupingSets = Max(phase->numsets, 1);
    3519       55396 :             int         setoff = 0;
    3520             : 
    3521      111532 :             for (int setno = 0; setno < processGroupingSets; setno++)
    3522             :             {
    3523       56136 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3524             :                                       pertrans, transno, setno, setoff, false,
    3525             :                                       nullcheck);
    3526       56136 :                 setoff++;
    3527             :             }
    3528             :         }
    3529             : 
    3530       59388 :         if (doHash)
    3531             :         {
    3532        4244 :             int         numHashes = aggstate->num_hashes;
    3533             :             int         setoff;
    3534             : 
    3535             :             /* in MIXED mode, there'll be preceding transition values */
    3536        4244 :             if (aggstate->aggstrategy != AGG_HASHED)
    3537         268 :                 setoff = aggstate->maxsets;
    3538             :             else
    3539        3976 :                 setoff = 0;
    3540             : 
    3541        9296 :             for (int setno = 0; setno < numHashes; setno++)
    3542             :             {
    3543        5052 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3544             :                                       pertrans, transno, setno, setoff, true,
    3545             :                                       nullcheck);
    3546        5052 :                 setoff++;
    3547             :             }
    3548             :         }
    3549             : 
    3550             :         /* adjust early bail out jump target(s) */
    3551       67326 :         foreach(bail, adjust_bailout)
    3552             :         {
    3553        7938 :             ExprEvalStep *as = &state->steps[lfirst_int(bail)];
    3554             : 
    3555        7938 :             if (as->opcode == EEOP_JUMP_IF_NOT_TRUE)
    3556             :             {
    3557             :                 Assert(as->d.jump.jumpdone == -1);
    3558         518 :                 as->d.jump.jumpdone = state->steps_len;
    3559             :             }
    3560        7420 :             else if (as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_ARGS ||
    3561         174 :                      as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_NULLS)
    3562             :             {
    3563             :                 Assert(as->d.agg_strict_input_check.jumpnull == -1);
    3564        7372 :                 as->d.agg_strict_input_check.jumpnull = state->steps_len;
    3565             :             }
    3566          48 :             else if (as->opcode == EEOP_AGG_STRICT_DESERIALIZE)
    3567             :             {
    3568             :                 Assert(as->d.agg_deserialize.jumpnull == -1);
    3569          48 :                 as->d.agg_deserialize.jumpnull = state->steps_len;
    3570             :             }
    3571             :             else
    3572             :                 Assert(false);
    3573             :         }
    3574             :     }
    3575             : 
    3576       58234 :     scratch.resvalue = NULL;
    3577       58234 :     scratch.resnull = NULL;
    3578       58234 :     scratch.opcode = EEOP_DONE;
    3579       58234 :     ExprEvalPushStep(state, &scratch);
    3580             : 
    3581       58234 :     ExecReadyExpr(state);
    3582             : 
    3583       58234 :     return state;
    3584             : }
    3585             : 
    3586             : /*
    3587             :  * Build transition/combine function invocation for a single transition
    3588             :  * value. This is separated from ExecBuildAggTrans() because there are
    3589             :  * multiple callsites (hash and sort in some grouping set cases).
    3590             :  */
    3591             : static void
    3592       61188 : ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
    3593             :                       ExprEvalStep *scratch,
    3594             :                       FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
    3595             :                       int transno, int setno, int setoff, bool ishash,
    3596             :                       bool nullcheck)
    3597             : {
    3598             :     ExprContext *aggcontext;
    3599       61188 :     int         adjust_jumpnull = -1;
    3600             : 
    3601       61188 :     if (ishash)
    3602        5052 :         aggcontext = aggstate->hashcontext;
    3603             :     else
    3604       56136 :         aggcontext = aggstate->aggcontexts[setno];
    3605             : 
    3606             :     /* add check for NULL pointer? */
    3607       61188 :     if (nullcheck)
    3608             :     {
    3609         272 :         scratch->opcode = EEOP_AGG_PLAIN_PERGROUP_NULLCHECK;
    3610         272 :         scratch->d.agg_plain_pergroup_nullcheck.setoff = setoff;
    3611             :         /* adjust later */
    3612         272 :         scratch->d.agg_plain_pergroup_nullcheck.jumpnull = -1;
    3613         272 :         ExprEvalPushStep(state, scratch);
    3614         272 :         adjust_jumpnull = state->steps_len - 1;
    3615             :     }
    3616             : 
    3617             :     /*
    3618             :      * Determine appropriate transition implementation.
    3619             :      *
    3620             :      * For non-ordered aggregates:
    3621             :      *
    3622             :      * If the initial value for the transition state doesn't exist in the
    3623             :      * pg_aggregate table then we will let the first non-NULL value returned
    3624             :      * from the outer procNode become the initial value. (This is useful for
    3625             :      * aggregates like max() and min().) The noTransValue flag signals that we
    3626             :      * need to do so. If true, generate a
    3627             :      * EEOP_AGG_INIT_STRICT_PLAIN_TRANS{,_BYVAL} step. This step also needs to
    3628             :      * do the work described next:
    3629             :      *
    3630             :      * If the function is strict, but does have an initial value, choose
    3631             :      * EEOP_AGG_STRICT_PLAIN_TRANS{,_BYVAL}, which skips the transition
    3632             :      * function if the transition value has become NULL (because a previous
    3633             :      * transition function returned NULL). This step also needs to do the work
    3634             :      * described next:
    3635             :      *
    3636             :      * Otherwise we call EEOP_AGG_PLAIN_TRANS{,_BYVAL}, which does not have to
    3637             :      * perform either of the above checks.
    3638             :      *
    3639             :      * Having steps with overlapping responsibilities is not nice, but
    3640             :      * aggregations are very performance sensitive, making this worthwhile.
    3641             :      *
    3642             :      * For ordered aggregates:
    3643             :      *
    3644             :      * Only need to choose between the faster path for a single ordered
    3645             :      * column, and the one between multiple columns. Checking strictness etc
    3646             :      * is done when finalizing the aggregate. See
    3647             :      * process_ordered_aggregate_{single, multi} and
    3648             :      * advance_transition_function.
    3649             :      */
    3650       61188 :     if (pertrans->numSortCols == 0)
    3651             :     {
    3652       29236 :         if (pertrans->transtypeByVal)
    3653             :         {
    3654       26920 :             if (fcinfo->flinfo->fn_strict &&
    3655       15262 :                 pertrans->initValueIsNull)
    3656        3618 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL;
    3657       23302 :             else if (fcinfo->flinfo->fn_strict)
    3658       11644 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL;
    3659             :             else
    3660       11658 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYVAL;
    3661             :         }
    3662             :         else
    3663             :         {
    3664        2316 :             if (fcinfo->flinfo->fn_strict &&
    3665        2130 :                 pertrans->initValueIsNull)
    3666         540 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYREF;
    3667        1776 :             else if (fcinfo->flinfo->fn_strict)
    3668        1590 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYREF;
    3669             :             else
    3670         186 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYREF;
    3671             :         }
    3672             :     }
    3673       31952 :     else if (pertrans->numInputs == 1)
    3674       12376 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_DATUM;
    3675             :     else
    3676       19576 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_TUPLE;
    3677             : 
    3678       61188 :     scratch->d.agg_trans.pertrans = pertrans;
    3679       61188 :     scratch->d.agg_trans.setno = setno;
    3680       61188 :     scratch->d.agg_trans.setoff = setoff;
    3681       61188 :     scratch->d.agg_trans.transno = transno;
    3682       61188 :     scratch->d.agg_trans.aggcontext = aggcontext;
    3683       61188 :     ExprEvalPushStep(state, scratch);
    3684             : 
    3685             :     /* fix up jumpnull */
    3686       61188 :     if (adjust_jumpnull != -1)
    3687             :     {
    3688         272 :         ExprEvalStep *as = &state->steps[adjust_jumpnull];
    3689             : 
    3690             :         Assert(as->opcode == EEOP_AGG_PLAIN_PERGROUP_NULLCHECK);
    3691             :         Assert(as->d.agg_plain_pergroup_nullcheck.jumpnull == -1);
    3692         272 :         as->d.agg_plain_pergroup_nullcheck.jumpnull = state->steps_len;
    3693             :     }
    3694       61188 : }
    3695             : 
    3696             : /*
    3697             :  * Build equality expression that can be evaluated using ExecQual(), returning
    3698             :  * true if the expression context's inner/outer tuple are NOT DISTINCT. I.e
    3699             :  * two nulls match, a null and a not-null don't match.
    3700             :  *
    3701             :  * desc: tuple descriptor of the to-be-compared tuples
    3702             :  * numCols: the number of attributes to be examined
    3703             :  * keyColIdx: array of attribute column numbers
    3704             :  * eqFunctions: array of function oids of the equality functions to use
    3705             :  * parent: parent executor node
    3706             :  */
    3707             : ExprState *
    3708       10928 : ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc,
    3709             :                        const TupleTableSlotOps *lops, const TupleTableSlotOps *rops,
    3710             :                        int numCols,
    3711             :                        const AttrNumber *keyColIdx,
    3712             :                        const Oid *eqfunctions,
    3713             :                        const Oid *collations,
    3714             :                        PlanState *parent)
    3715             : {
    3716       10928 :     ExprState  *state = makeNode(ExprState);
    3717       10928 :     ExprEvalStep scratch = {0};
    3718       10928 :     int         maxatt = -1;
    3719       10928 :     List       *adjust_jumps = NIL;
    3720             :     ListCell   *lc;
    3721             : 
    3722             :     /*
    3723             :      * When no columns are actually compared, the result's always true. See
    3724             :      * special case in ExecQual().
    3725             :      */
    3726       10928 :     if (numCols == 0)
    3727          32 :         return NULL;
    3728             : 
    3729       10896 :     state->expr = NULL;
    3730       10896 :     state->flags = EEO_FLAG_IS_QUAL;
    3731       10896 :     state->parent = parent;
    3732             : 
    3733       10896 :     scratch.resvalue = &state->resvalue;
    3734       10896 :     scratch.resnull = &state->resnull;
    3735             : 
    3736             :     /* compute max needed attribute */
    3737       25972 :     for (int natt = 0; natt < numCols; natt++)
    3738             :     {
    3739       15076 :         int         attno = keyColIdx[natt];
    3740             : 
    3741       15076 :         if (attno > maxatt)
    3742       14924 :             maxatt = attno;
    3743             :     }
    3744             :     Assert(maxatt >= 0);
    3745             : 
    3746             :     /* push deform steps */
    3747       10896 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    3748       10896 :     scratch.d.fetch.last_var = maxatt;
    3749       10896 :     scratch.d.fetch.fixed = false;
    3750       10896 :     scratch.d.fetch.known_desc = ldesc;
    3751       10896 :     scratch.d.fetch.kind = lops;
    3752       10896 :     if (ExecComputeSlotInfo(state, &scratch))
    3753        9572 :         ExprEvalPushStep(state, &scratch);
    3754             : 
    3755       10896 :     scratch.opcode = EEOP_OUTER_FETCHSOME;
    3756       10896 :     scratch.d.fetch.last_var = maxatt;
    3757       10896 :     scratch.d.fetch.fixed = false;
    3758       10896 :     scratch.d.fetch.known_desc = rdesc;
    3759       10896 :     scratch.d.fetch.kind = rops;
    3760       10896 :     if (ExecComputeSlotInfo(state, &scratch))
    3761       10896 :         ExprEvalPushStep(state, &scratch);
    3762             : 
    3763             :     /*
    3764             :      * Start comparing at the last field (least significant sort key). That's
    3765             :      * the most likely to be different if we are dealing with sorted input.
    3766             :      */
    3767       25972 :     for (int natt = numCols; --natt >= 0;)
    3768             :     {
    3769       15076 :         int         attno = keyColIdx[natt];
    3770       15076 :         Form_pg_attribute latt = TupleDescAttr(ldesc, attno - 1);
    3771       15076 :         Form_pg_attribute ratt = TupleDescAttr(rdesc, attno - 1);
    3772       15076 :         Oid         foid = eqfunctions[natt];
    3773       15076 :         Oid         collid = collations[natt];
    3774             :         FmgrInfo   *finfo;
    3775             :         FunctionCallInfo fcinfo;
    3776             :         AclResult   aclresult;
    3777             : 
    3778             :         /* Check permission to call function */
    3779       15076 :         aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
    3780       15076 :         if (aclresult != ACLCHECK_OK)
    3781           0 :             aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
    3782             : 
    3783       15076 :         InvokeFunctionExecuteHook(foid);
    3784             : 
    3785             :         /* Set up the primary fmgr lookup information */
    3786       15076 :         finfo = palloc0(sizeof(FmgrInfo));
    3787       15076 :         fcinfo = palloc0(SizeForFunctionCallInfo(2));
    3788       15076 :         fmgr_info(foid, finfo);
    3789       15076 :         fmgr_info_set_expr(NULL, finfo);
    3790       15076 :         InitFunctionCallInfoData(*fcinfo, finfo, 2,
    3791             :                                  collid, NULL, NULL);
    3792             : 
    3793             :         /* left arg */
    3794       15076 :         scratch.opcode = EEOP_INNER_VAR;
    3795       15076 :         scratch.d.var.attnum = attno - 1;
    3796       15076 :         scratch.d.var.vartype = latt->atttypid;
    3797       15076 :         scratch.resvalue = &fcinfo->args[0].value;
    3798       15076 :         scratch.resnull = &fcinfo->args[0].isnull;
    3799       15076 :         ExprEvalPushStep(state, &scratch);
    3800             : 
    3801             :         /* right arg */
    3802       15076 :         scratch.opcode = EEOP_OUTER_VAR;
    3803       15076 :         scratch.d.var.attnum = attno - 1;
    3804       15076 :         scratch.d.var.vartype = ratt->atttypid;
    3805       15076 :         scratch.resvalue = &fcinfo->args[1].value;
    3806       15076 :         scratch.resnull = &fcinfo->args[1].isnull;
    3807       15076 :         ExprEvalPushStep(state, &scratch);
    3808             : 
    3809             :         /* evaluate distinctness */
    3810       15076 :         scratch.opcode = EEOP_NOT_DISTINCT;
    3811       15076 :         scratch.d.func.finfo = finfo;
    3812       15076 :         scratch.d.func.fcinfo_data = fcinfo;
    3813       15076 :         scratch.d.func.fn_addr = finfo->fn_addr;
    3814       15076 :         scratch.d.func.nargs = 2;
    3815       15076 :         scratch.resvalue = &state->resvalue;
    3816       15076 :         scratch.resnull = &state->resnull;
    3817       15076 :         ExprEvalPushStep(state, &scratch);
    3818             : 
    3819             :         /* then emit EEOP_QUAL to detect if result is false (or null) */
    3820       15076 :         scratch.opcode = EEOP_QUAL;
    3821       15076 :         scratch.d.qualexpr.jumpdone = -1;
    3822       15076 :         scratch.resvalue = &state->resvalue;
    3823       15076 :         scratch.resnull = &state->resnull;
    3824       15076 :         ExprEvalPushStep(state, &scratch);
    3825       15076 :         adjust_jumps = lappend_int(adjust_jumps,
    3826       15076 :                                    state->steps_len - 1);
    3827             :     }
    3828             : 
    3829             :     /* adjust jump targets */
    3830       25972 :     foreach(lc, adjust_jumps)
    3831             :     {
    3832       15076 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    3833             : 
    3834             :         Assert(as->opcode == EEOP_QUAL);
    3835             :         Assert(as->d.qualexpr.jumpdone == -1);
    3836       15076 :         as->d.qualexpr.jumpdone = state->steps_len;
    3837             :     }
    3838             : 
    3839       10896 :     scratch.resvalue = NULL;
    3840       10896 :     scratch.resnull = NULL;
    3841       10896 :     scratch.opcode = EEOP_DONE;
    3842       10896 :     ExprEvalPushStep(state, &scratch);
    3843             : 
    3844       10896 :     ExecReadyExpr(state);
    3845             : 
    3846       10896 :     return state;
    3847             : }
    3848             : 
    3849             : /*
    3850             :  * Build equality expression that can be evaluated using ExecQual(), returning
    3851             :  * true if the expression context's inner/outer tuples are equal.  Datums in
    3852             :  * the inner/outer slots are assumed to be in the same order and quantity as
    3853             :  * the 'eqfunctions' parameter.  NULLs are treated as equal.
    3854             :  *
    3855             :  * desc: tuple descriptor of the to-be-compared tuples
    3856             :  * lops: the slot ops for the inner tuple slots
    3857             :  * rops: the slot ops for the outer tuple slots
    3858             :  * eqFunctions: array of function oids of the equality functions to use
    3859             :  * this must be the same length as the 'param_exprs' list.
    3860             :  * collations: collation Oids to use for equality comparison. Must be the
    3861             :  * same length as the 'param_exprs' list.
    3862             :  * parent: parent executor node
    3863             :  */
    3864             : ExprState *
    3865         924 : ExecBuildParamSetEqual(TupleDesc desc,
    3866             :                        const TupleTableSlotOps *lops,
    3867             :                        const TupleTableSlotOps *rops,
    3868             :                        const Oid *eqfunctions,
    3869             :                        const Oid *collations,
    3870             :                        const List *param_exprs,
    3871             :                        PlanState *parent)
    3872             : {
    3873         924 :     ExprState  *state = makeNode(ExprState);
    3874         924 :     ExprEvalStep scratch = {0};
    3875         924 :     int         maxatt = list_length(param_exprs);
    3876         924 :     List       *adjust_jumps = NIL;
    3877             :     ListCell   *lc;
    3878             : 
    3879         924 :     state->expr = NULL;
    3880         924 :     state->flags = EEO_FLAG_IS_QUAL;
    3881         924 :     state->parent = parent;
    3882             : 
    3883         924 :     scratch.resvalue = &state->resvalue;
    3884         924 :     scratch.resnull = &state->resnull;
    3885             : 
    3886             :     /* push deform steps */
    3887         924 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    3888         924 :     scratch.d.fetch.last_var = maxatt;
    3889         924 :     scratch.d.fetch.fixed = false;
    3890         924 :     scratch.d.fetch.known_desc = desc;
    3891         924 :     scratch.d.fetch.kind = lops;
    3892         924 :     if (ExecComputeSlotInfo(state, &scratch))
    3893         924 :         ExprEvalPushStep(state, &scratch);
    3894             : 
    3895         924 :     scratch.opcode = EEOP_OUTER_FETCHSOME;
    3896         924 :     scratch.d.fetch.last_var = maxatt;
    3897         924 :     scratch.d.fetch.fixed = false;
    3898         924 :     scratch.d.fetch.known_desc = desc;
    3899         924 :     scratch.d.fetch.kind = rops;
    3900         924 :     if (ExecComputeSlotInfo(state, &scratch))
    3901           0 :         ExprEvalPushStep(state, &scratch);
    3902             : 
    3903        1860 :     for (int attno = 0; attno < maxatt; attno++)
    3904             :     {
    3905         936 :         Form_pg_attribute att = TupleDescAttr(desc, attno);
    3906         936 :         Oid         foid = eqfunctions[attno];
    3907         936 :         Oid         collid = collations[attno];
    3908             :         FmgrInfo   *finfo;
    3909             :         FunctionCallInfo fcinfo;
    3910             :         AclResult   aclresult;
    3911             : 
    3912             :         /* Check permission to call function */
    3913         936 :         aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
    3914         936 :         if (aclresult != ACLCHECK_OK)
    3915           0 :             aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
    3916             : 
    3917         936 :         InvokeFunctionExecuteHook(foid);
    3918             : 
    3919             :         /* Set up the primary fmgr lookup information */
    3920         936 :         finfo = palloc0(sizeof(FmgrInfo));
    3921         936 :         fcinfo = palloc0(SizeForFunctionCallInfo(2));
    3922         936 :         fmgr_info(foid, finfo);
    3923         936 :         fmgr_info_set_expr(NULL, finfo);
    3924         936 :         InitFunctionCallInfoData(*fcinfo, finfo, 2,
    3925             :                                  collid, NULL, NULL);
    3926             : 
    3927             :         /* left arg */
    3928         936 :         scratch.opcode = EEOP_INNER_VAR;
    3929         936 :         scratch.d.var.attnum = attno;
    3930         936 :         scratch.d.var.vartype = att->atttypid;
    3931         936 :         scratch.resvalue = &fcinfo->args[0].value;
    3932         936 :         scratch.resnull = &fcinfo->args[0].isnull;
    3933         936 :         ExprEvalPushStep(state, &scratch);
    3934             : 
    3935             :         /* right arg */
    3936         936 :         scratch.opcode = EEOP_OUTER_VAR;
    3937         936 :         scratch.d.var.attnum = attno;
    3938         936 :         scratch.d.var.vartype = att->atttypid;
    3939         936 :         scratch.resvalue = &fcinfo->args[1].value;
    3940         936 :         scratch.resnull = &fcinfo->args[1].isnull;
    3941         936 :         ExprEvalPushStep(state, &scratch);
    3942             : 
    3943             :         /* evaluate distinctness */
    3944         936 :         scratch.opcode = EEOP_NOT_DISTINCT;
    3945         936 :         scratch.d.func.finfo = finfo;
    3946         936 :         scratch.d.func.fcinfo_data = fcinfo;
    3947         936 :         scratch.d.func.fn_addr = finfo->fn_addr;
    3948         936 :         scratch.d.func.nargs = 2;
    3949         936 :         scratch.resvalue = &state->resvalue;
    3950         936 :         scratch.resnull = &state->resnull;
    3951         936 :         ExprEvalPushStep(state, &scratch);
    3952             : 
    3953             :         /* then emit EEOP_QUAL to detect if result is false (or null) */
    3954         936 :         scratch.opcode = EEOP_QUAL;
    3955         936 :         scratch.d.qualexpr.jumpdone = -1;
    3956         936 :         scratch.resvalue = &state->resvalue;
    3957         936 :         scratch.resnull = &state->resnull;
    3958         936 :         ExprEvalPushStep(state, &scratch);
    3959         936 :         adjust_jumps = lappend_int(adjust_jumps,
    3960         936 :                                    state->steps_len - 1);
    3961             :     }
    3962             : 
    3963             :     /* adjust jump targets */
    3964        1860 :     foreach(lc, adjust_jumps)
    3965             :     {
    3966         936 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    3967             : 
    3968             :         Assert(as->opcode == EEOP_QUAL);
    3969             :         Assert(as->d.qualexpr.jumpdone == -1);
    3970         936 :         as->d.qualexpr.jumpdone = state->steps_len;
    3971             :     }
    3972             : 
    3973         924 :     scratch.resvalue = NULL;
    3974         924 :     scratch.resnull = NULL;
    3975         924 :     scratch.opcode = EEOP_DONE;
    3976         924 :     ExprEvalPushStep(state, &scratch);
    3977             : 
    3978         924 :     ExecReadyExpr(state);
    3979             : 
    3980         924 :     return state;
    3981             : }

Generated by: LCOV version 1.14