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

Generated by: LCOV version 1.14