]> granicus.if.org Git - postgresql/blobdiff - src/backend/optimizer/plan/createplan.c
Fix PARAM_EXEC assignment mechanism to be safe in the presence of WITH.
[postgresql] / src / backend / optimizer / plan / createplan.c
index aea42b1dd461a3ef5d94bee79b980bdadfd57551..030f420c90eb37946ee333250de54af61d9b82d7 100644 (file)
@@ -30,6 +30,7 @@
 #include "optimizer/placeholder.h"
 #include "optimizer/plancat.h"
 #include "optimizer/planmain.h"
+#include "optimizer/planner.h"
 #include "optimizer/predtest.h"
 #include "optimizer/restrictinfo.h"
 #include "optimizer/subselect.h"
@@ -60,7 +61,7 @@ static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
                                                BitmapHeapPath *best_path,
                                                List *tlist, List *scan_clauses);
 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
-                                         List **qual, List **indexqual);
+                                         List **qual, List **indexqual, List **indexECs);
 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
                                        List *tlist, List *scan_clauses);
 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
@@ -83,6 +84,8 @@ static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
                                         Plan *outer_plan, Plan *inner_plan);
 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
+static void process_subquery_nestloop_params(PlannerInfo *root,
+                                                                List *subplan_params);
 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
@@ -120,8 +123,6 @@ static CteScan *make_ctescan(List *qptlist, List *qpqual,
                         Index scanrelid, int ctePlanId, int cteParam);
 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
                                   Index scanrelid, int wtParam);
-static ForeignScan *make_foreignscan(List *qptlist, List *qpqual,
-                                Index scanrelid, bool fsSystemCol, FdwPlan *fdwplan);
 static BitmapAnd *make_bitmap_and(List *bitmapplans);
 static BitmapOr *make_bitmap_or(List *bitmapplans);
 static NestLoop *make_nestloop(List *tlist,
@@ -154,12 +155,17 @@ static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
                  double limit_tuples);
 static Plan *prepare_sort_from_pathkeys(PlannerInfo *root,
                                                   Plan *lefttree, List *pathkeys,
+                                                  Relids relids,
+                                                  const AttrNumber *reqColIdx,
                                                   bool adjust_tlist_in_place,
                                                   int *p_numsortkeys,
                                                   AttrNumber **p_sortColIdx,
                                                   Oid **p_sortOperators,
                                                   Oid **p_collations,
                                                   bool **p_nullsFirst);
+static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
+                                          TargetEntry *tle,
+                                          Relids relids);
 static Material *make_material(Plan *lefttree);
 
 
@@ -183,6 +189,9 @@ create_plan(PlannerInfo *root, Path *best_path)
 {
        Plan       *plan;
 
+       /* plan_params should not be in use in current query level */
+       Assert(root->plan_params == NIL);
+
        /* Initialize this module's private workspace in PlannerInfo */
        root->curOuterRels = NULL;
        root->curOuterParams = NIL;
@@ -194,6 +203,12 @@ create_plan(PlannerInfo *root, Path *best_path)
        if (root->curOuterParams != NIL)
                elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
 
+       /*
+        * Reset plan_params to ensure param IDs used for nestloop params are not
+        * re-used later
+        */
+       root->plan_params = NIL;
+
        return plan;
 }
 
@@ -293,8 +308,19 @@ create_scan_plan(PlannerInfo *root, Path *best_path)
                }
        }
        else
+       {
                tlist = build_relation_tlist(rel);
 
+               /*
+                * If it's a parameterized otherrel, there might be lateral references
+                * in the tlist, which need to be replaced with Params.  This cannot
+                * happen for regular baserels, though.  Note use_physical_tlist()
+                * always fails for otherrels, so we don't need to check this above.
+                */
+               if (rel->reloptkind != RELOPT_BASEREL && best_path->param_info)
+                       tlist = (List *) replace_nestloop_params(root, (Node *) tlist);
+       }
+
        /*
         * Extract the relevant restriction clauses from the parent relation. The
         * executor must apply all these restrictions during the scan, except for
@@ -302,6 +328,16 @@ create_scan_plan(PlannerInfo *root, Path *best_path)
         */
        scan_clauses = rel->baserestrictinfo;
 
+       /*
+        * If this is a parameterized scan, we also need to enforce all the join
+        * clauses available from the outer relation(s).
+        *
+        * For paranoia's sake, don't modify the stored baserestrictinfo list.
+        */
+       if (best_path->param_info)
+               scan_clauses = list_concat(list_copy(scan_clauses),
+                                                                  best_path->param_info->ppi_clauses);
+
        switch (best_path->pathtype)
        {
                case T_SeqScan:
@@ -708,6 +744,8 @@ create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
 
        /* Compute sort column info, and adjust MergeAppend's tlist as needed */
        (void) prepare_sort_from_pathkeys(root, plan, pathkeys,
+                                                                         NULL,
+                                                                         NULL,
                                                                          true,
                                                                          &node->numCols,
                                                                          &node->sortColIdx,
@@ -735,6 +773,8 @@ create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
 
                /* Compute sort column info, and adjust subplan's tlist as needed */
                subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys,
+                                                                                        subpath->parent->relids,
+                                                                                        node->sortColIdx,
                                                                                         false,
                                                                                         &numsortkeys,
                                                                                         &sortColIdx,
@@ -1053,6 +1093,13 @@ create_seqscan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+       }
+
        scan_plan = make_seqscan(tlist,
                                                         scan_clauses,
                                                         scan_relid);
@@ -1111,35 +1158,30 @@ create_indexscan_plan(PlannerInfo *root,
         */
        fixed_indexorderbys = fix_indexorderby_references(root, best_path);
 
-       /*
-        * If this is a parameterized scan, the indexclauses will contain join
-        * clauses that are not present in scan_clauses (since the passed-in value
-        * is just the rel's baserestrictinfo list).  We must add these clauses to
-        * scan_clauses to ensure they get checked.  In most cases we will remove
-        * the join clauses again below, but if a join clause contains a special
-        * operator, we need to make sure it gets into the scan_clauses.
-        *
-        * Note: pointer comparison should be enough to determine RestrictInfo
-        * matches.
-        */
-       if (best_path->path.required_outer)
-               scan_clauses = list_union_ptr(scan_clauses, best_path->indexclauses);
-
        /*
         * The qpqual list must contain all restrictions not automatically handled
-        * by the index.  All the predicates in the indexquals will be checked
-        * (either by the index itself, or by nodeIndexscan.c), but if there are
-        * any "special" operators involved then they must be included in qpqual.
-        * The upshot is that qpqual must contain scan_clauses minus whatever
-        * appears in indexquals.
+        * by the index, other than pseudoconstant clauses which will be handled
+        * by a separate gating plan node.      All the predicates in the indexquals
+        * will be checked (either by the index itself, or by nodeIndexscan.c),
+        * but if there are any "special" operators involved then they must be
+        * included in qpqual.  The upshot is that qpqual must contain
+        * scan_clauses minus whatever appears in indexquals.
         *
         * In normal cases simple pointer equality checks will be enough to spot
-        * duplicate RestrictInfos, so we try that first.  In some situations
-        * (particularly with OR'd index conditions) we may have scan_clauses that
-        * are not equal to, but are logically implied by, the index quals; so we
-        * also try a predicate_implied_by() check to see if we can discard quals
-        * that way.  (predicate_implied_by assumes its first input contains only
-        * immutable functions, so we have to check that.)
+        * duplicate RestrictInfos, so we try that first.
+        *
+        * Another common case is that a scan_clauses entry is generated from the
+        * same EquivalenceClass as some indexqual, and is therefore redundant
+        * with it, though not equal.  (This happens when indxpath.c prefers a
+        * different derived equality than what generate_join_implied_equalities
+        * picked for a parameterized scan's ppi_clauses.)
+        *
+        * In some situations (particularly with OR'd index conditions) we may
+        * have scan_clauses that are not equal to, but are logically implied by,
+        * the index quals; so we also try a predicate_implied_by() check to see
+        * if we can discard quals that way.  (predicate_implied_by assumes its
+        * first input contains only immutable functions, so we have to check
+        * that.)
         *
         * We can also discard quals that are implied by a partial index's
         * predicate, but only in a plain SELECT; when scanning a target relation
@@ -1155,20 +1197,22 @@ create_indexscan_plan(PlannerInfo *root,
                if (rinfo->pseudoconstant)
                        continue;                       /* we may drop pseudoconstants here */
                if (list_member_ptr(indexquals, rinfo))
-                       continue;
+                       continue;                       /* simple duplicate */
+               if (is_redundant_derived_clause(rinfo, indexquals))
+                       continue;                       /* derived from same EquivalenceClass */
                if (!contain_mutable_functions((Node *) rinfo->clause))
                {
                        List       *clausel = list_make1(rinfo->clause);
 
                        if (predicate_implied_by(clausel, indexquals))
-                               continue;
+                               continue;               /* provably implied by indexquals */
                        if (best_path->indexinfo->indpred)
                        {
                                if (baserelid != root->parse->resultRelation &&
                                        get_parse_rowmark(root->parse, baserelid) == NULL)
                                        if (predicate_implied_by(clausel,
                                                                                         best_path->indexinfo->indpred))
-                                               continue;
+                                               continue;               /* implied by index predicate */
                        }
                }
                qpqual = lappend(qpqual, rinfo);
@@ -1189,7 +1233,7 @@ create_indexscan_plan(PlannerInfo *root,
         * it'd break the comparisons to predicates above ... (or would it?  Those
         * wouldn't have outer refs)
         */
-       if (best_path->path.required_outer)
+       if (best_path->path.param_info)
        {
                stripped_indexquals = (List *)
                        replace_nestloop_params(root, (Node *) stripped_indexquals);
@@ -1207,7 +1251,7 @@ create_indexscan_plan(PlannerInfo *root,
                                                                                                indexoid,
                                                                                                fixed_indexquals,
                                                                                                fixed_indexorderbys,
-                                                                                               best_path->indexinfo->indextlist,
+                                                                                       best_path->indexinfo->indextlist,
                                                                                                best_path->indexscandir);
        else
                scan_plan = (Scan *) make_indexscan(tlist,
@@ -1240,6 +1284,7 @@ create_bitmap_scan_plan(PlannerInfo *root,
        Plan       *bitmapqualplan;
        List       *bitmapqualorig;
        List       *indexquals;
+       List       *indexECs;
        List       *qpqual;
        ListCell   *l;
        BitmapHeapScan *scan_plan;
@@ -1250,66 +1295,63 @@ create_bitmap_scan_plan(PlannerInfo *root,
 
        /* Process the bitmapqual tree into a Plan tree and qual lists */
        bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
-                                                                                  &bitmapqualorig, &indexquals);
-
-       /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
-       scan_clauses = extract_actual_clauses(scan_clauses, false);
-
-       /*
-        * If this is a parameterized scan, the indexclauses will contain join clauses
-        * that are not present in scan_clauses (since the passed-in value is just
-        * the rel's baserestrictinfo list).  We must add these clauses to
-        * scan_clauses to ensure they get checked.  In most cases we will remove
-        * the join clauses again below, but if a join clause contains a special
-        * operator, we need to make sure it gets into the scan_clauses.
-        */
-       if (best_path->path.required_outer)
-       {
-               scan_clauses = list_concat_unique(scan_clauses, bitmapqualorig);
-       }
+                                                                                  &bitmapqualorig, &indexquals,
+                                                                                  &indexECs);
 
        /*
         * The qpqual list must contain all restrictions not automatically handled
-        * by the index.  All the predicates in the indexquals will be checked
-        * (either by the index itself, or by nodeBitmapHeapscan.c), but if there
-        * are any "special" operators involved then they must be added to qpqual.
-        * The upshot is that qpqual must contain scan_clauses minus whatever
-        * appears in indexquals.
+        * by the index, other than pseudoconstant clauses which will be handled
+        * by a separate gating plan node.      All the predicates in the indexquals
+        * will be checked (either by the index itself, or by
+        * nodeBitmapHeapscan.c), but if there are any "special" operators
+        * involved then they must be added to qpqual.  The upshot is that qpqual
+        * must contain scan_clauses minus whatever appears in indexquals.
+        *
+        * This loop is similar to the comparable code in create_indexscan_plan(),
+        * but with some differences because it has to compare the scan clauses to
+        * stripped (no RestrictInfos) indexquals.      See comments there for more
+        * info.
         *
         * In normal cases simple equal() checks will be enough to spot duplicate
-        * clauses, so we try that first.  In some situations (particularly with
-        * OR'd index conditions) we may have scan_clauses that are not equal to,
-        * but are logically implied by, the index quals; so we also try a
-        * predicate_implied_by() check to see if we can discard quals that way.
-        * (predicate_implied_by assumes its first input contains only immutable
-        * functions, so we have to check that.)
+        * clauses, so we try that first.  We next see if the scan clause is
+        * redundant with any top-level indexqual by virtue of being generated
+        * from the same EC.  After that, try predicate_implied_by().
         *
         * Unlike create_indexscan_plan(), we need take no special thought here
         * for partial index predicates; this is because the predicate conditions
         * are already listed in bitmapqualorig and indexquals.  Bitmap scans have
         * to do it that way because predicate conditions need to be rechecked if
-        * the scan becomes lossy.
+        * the scan becomes lossy, so they have to be included in bitmapqualorig.
         */
        qpqual = NIL;
        foreach(l, scan_clauses)
        {
-               Node       *clause = (Node *) lfirst(l);
+               RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+               Node       *clause = (Node *) rinfo->clause;
 
+               Assert(IsA(rinfo, RestrictInfo));
+               if (rinfo->pseudoconstant)
+                       continue;                       /* we may drop pseudoconstants here */
                if (list_member(indexquals, clause))
-                       continue;
+                       continue;                       /* simple duplicate */
+               if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
+                       continue;                       /* derived from same EquivalenceClass */
                if (!contain_mutable_functions(clause))
                {
                        List       *clausel = list_make1(clause);
 
                        if (predicate_implied_by(clausel, indexquals))
-                               continue;
+                               continue;               /* provably implied by indexquals */
                }
-               qpqual = lappend(qpqual, clause);
+               qpqual = lappend(qpqual, rinfo);
        }
 
        /* Sort clauses into best execution order */
        qpqual = order_qual_clauses(root, qpqual);
 
+       /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
+       qpqual = extract_actual_clauses(qpqual, false);
+
        /*
         * When dealing with special operators, we will at this point have
         * duplicate clauses in qpqual and bitmapqualorig.      We may as well drop
@@ -1318,6 +1360,19 @@ create_bitmap_scan_plan(PlannerInfo *root,
         */
        bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
 
+       /*
+        * We have to replace any outer-relation variables with nestloop params in
+        * the qpqual and bitmapqualorig expressions.  (This was already done for
+        * expressions attached to plan nodes in the bitmapqualplan tree.)
+        */
+       if (best_path->path.param_info)
+       {
+               qpqual = (List *)
+                       replace_nestloop_params(root, (Node *) qpqual);
+               bitmapqualorig = (List *)
+                       replace_nestloop_params(root, (Node *) bitmapqualorig);
+       }
+
        /* Finally ready to build the plan node */
        scan_plan = make_bitmap_heapscan(tlist,
                                                                         qpqual,
@@ -1342,12 +1397,20 @@ create_bitmap_scan_plan(PlannerInfo *root,
  * predicates, because we have to recheck predicates as well as index
  * conditions if the bitmap scan becomes lossy.
  *
+ * In addition, we return a list of EquivalenceClass pointers for all the
+ * top-level indexquals that were possibly-redundantly derived from ECs.
+ * This allows removal of scan_clauses that are redundant with such quals.
+ * (We do not attempt to detect such redundancies for quals that are within
+ * OR subtrees.  This could be done in a less hacky way if we returned the
+ * indexquals in RestrictInfo form, but that would be slower and still pretty
+ * messy, since we'd have to build new RestrictInfos in many cases.)
+ *
  * Note: if you find yourself changing this, you probably need to change
  * make_restrictinfo_from_bitmapqual too.
  */
 static Plan *
 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
-                                         List **qual, List **indexqual)
+                                         List **qual, List **indexqual, List **indexECs)
 {
        Plan       *plan;
 
@@ -1357,6 +1420,7 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                List       *subplans = NIL;
                List       *subquals = NIL;
                List       *subindexquals = NIL;
+               List       *subindexECs = NIL;
                ListCell   *l;
 
                /*
@@ -1371,12 +1435,16 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                        Plan       *subplan;
                        List       *subqual;
                        List       *subindexqual;
+                       List       *subindexEC;
 
                        subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
-                                                                                       &subqual, &subindexqual);
+                                                                                       &subqual, &subindexqual,
+                                                                                       &subindexEC);
                        subplans = lappend(subplans, subplan);
                        subquals = list_concat_unique(subquals, subqual);
                        subindexquals = list_concat_unique(subindexquals, subindexqual);
+                       /* Duplicates in indexECs aren't worth getting rid of */
+                       subindexECs = list_concat(subindexECs, subindexEC);
                }
                plan = (Plan *) make_bitmap_and(subplans);
                plan->startup_cost = apath->path.startup_cost;
@@ -1386,6 +1454,7 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                plan->plan_width = 0;   /* meaningless */
                *qual = subquals;
                *indexqual = subindexquals;
+               *indexECs = subindexECs;
        }
        else if (IsA(bitmapqual, BitmapOrPath))
        {
@@ -1411,9 +1480,11 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                        Plan       *subplan;
                        List       *subqual;
                        List       *subindexqual;
+                       List       *subindexEC;
 
                        subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
-                                                                                       &subqual, &subindexqual);
+                                                                                       &subqual, &subindexqual,
+                                                                                       &subindexEC);
                        subplans = lappend(subplans, subplan);
                        if (subqual == NIL)
                                const_true_subqual = true;
@@ -1462,11 +1533,13 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                        *indexqual = subindexquals;
                else
                        *indexqual = list_make1(make_orclause(subindexquals));
+               *indexECs = NIL;
        }
        else if (IsA(bitmapqual, IndexPath))
        {
                IndexPath  *ipath = (IndexPath *) bitmapqual;
                IndexScan  *iscan;
+               List       *subindexECs;
                ListCell   *l;
 
                /* Use the regular indexscan plan build machinery... */
@@ -1501,18 +1574,15 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
                                *indexqual = lappend(*indexqual, pred);
                        }
                }
-
-               /*
-                * Replace outer-relation variables with nestloop params, but only
-                * after doing the above comparisons to index predicates.
-                */
-               if (ipath->path.required_outer)
+               subindexECs = NIL;
+               foreach(l, ipath->indexquals)
                {
-                       *qual = (List *)
-                               replace_nestloop_params(root, (Node *) *qual);
-                       *indexqual = (List *)
-                               replace_nestloop_params(root, (Node *) *indexqual);
+                       RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+
+                       if (rinfo->parent_ec)
+                               subindexECs = lappend(subindexECs, rinfo->parent_ec);
                }
+               *indexECs = subindexECs;
        }
        else
        {
@@ -1534,6 +1604,7 @@ create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
 {
        TidScan    *scan_plan;
        Index           scan_relid = best_path->path.parent->relid;
+       List       *tidquals = best_path->tidquals;
        List       *ortidquals;
 
        /* it should be a base rel... */
@@ -1546,11 +1617,20 @@ create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->path.param_info)
+       {
+               tidquals = (List *)
+                       replace_nestloop_params(root, (Node *) tidquals);
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+       }
+
        /*
         * Remove any clauses that are TID quals.  This is a bit tricky since the
         * tidquals list has implicit OR semantics.
         */
-       ortidquals = best_path->tidquals;
+       ortidquals = tidquals;
        if (list_length(ortidquals) > 1)
                ortidquals = list_make1(make_orclause(ortidquals));
        scan_clauses = list_difference(scan_clauses, ortidquals);
@@ -1558,7 +1638,7 @@ create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
        scan_plan = make_tidscan(tlist,
                                                         scan_clauses,
                                                         scan_relid,
-                                                        best_path->tidquals);
+                                                        tidquals);
 
        copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
 
@@ -1587,6 +1667,15 @@ create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+               process_subquery_nestloop_params(root,
+                                                                                best_path->parent->subplan_params);
+       }
+
        scan_plan = make_subqueryscan(tlist,
                                                                  scan_clauses,
                                                                  scan_relid,
@@ -1609,11 +1698,13 @@ create_functionscan_plan(PlannerInfo *root, Path *best_path,
        FunctionScan *scan_plan;
        Index           scan_relid = best_path->parent->relid;
        RangeTblEntry *rte;
+       Node       *funcexpr;
 
        /* it should be a function base rel... */
        Assert(scan_relid > 0);
        rte = planner_rt_fetch(scan_relid, root);
        Assert(rte->rtekind == RTE_FUNCTION);
+       funcexpr = rte->funcexpr;
 
        /* Sort clauses into best execution order */
        scan_clauses = order_qual_clauses(root, scan_clauses);
@@ -1621,8 +1712,17 @@ create_functionscan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+               /* The func expression itself could contain nestloop params, too */
+               funcexpr = replace_nestloop_params(root, funcexpr);
+       }
+
        scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
-                                                                 rte->funcexpr,
+                                                                 funcexpr,
                                                                  rte->eref->colnames,
                                                                  rte->funccoltypes,
                                                                  rte->funccoltypmods,
@@ -1645,11 +1745,13 @@ create_valuesscan_plan(PlannerInfo *root, Path *best_path,
        ValuesScan *scan_plan;
        Index           scan_relid = best_path->parent->relid;
        RangeTblEntry *rte;
+       List       *values_lists;
 
        /* it should be a values base rel... */
        Assert(scan_relid > 0);
        rte = planner_rt_fetch(scan_relid, root);
        Assert(rte->rtekind == RTE_VALUES);
+       values_lists = rte->values_lists;
 
        /* Sort clauses into best execution order */
        scan_clauses = order_qual_clauses(root, scan_clauses);
@@ -1657,8 +1759,18 @@ create_valuesscan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+               /* The values lists could contain nestloop params, too */
+               values_lists = (List *)
+                       replace_nestloop_params(root, (Node *) values_lists);
+       }
+
        scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
-                                                               rte->values_lists);
+                                                               values_lists);
 
        copy_path_costsize(&scan_plan->scan.plan, best_path);
 
@@ -1743,6 +1855,13 @@ create_ctescan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+       }
+
        scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
                                                         plan_id, cte_param_id);
 
@@ -1796,6 +1915,13 @@ create_worktablescan_plan(PlannerInfo *root, Path *best_path,
        /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
        scan_clauses = extract_actual_clauses(scan_clauses, false);
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->param_info)
+       {
+               scan_clauses = (List *)
+                       replace_nestloop_params(root, (Node *) scan_clauses);
+       }
+
        scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
                                                                   cteroot->wt_param_id);
 
@@ -1817,7 +1943,6 @@ create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
        RelOptInfo *rel = best_path->path.parent;
        Index           scan_relid = rel->relid;
        RangeTblEntry *rte;
-       bool            fsSystemCol;
        int                     i;
 
        /* it should be a base rel... */
@@ -1826,31 +1951,56 @@ create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
        rte = planner_rt_fetch(scan_relid, root);
        Assert(rte->rtekind == RTE_RELATION);
 
-       /* Sort clauses into best execution order */
+       /*
+        * Sort clauses into best execution order.      We do this first since the FDW
+        * might have more info than we do and wish to adjust the ordering.
+        */
        scan_clauses = order_qual_clauses(root, scan_clauses);
 
-       /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
-       scan_clauses = extract_actual_clauses(scan_clauses, false);
+       /*
+        * Let the FDW perform its processing on the restriction clauses and
+        * generate the plan node.      Note that the FDW might remove restriction
+        * clauses that it intends to execute remotely, or even add more (if it
+        * has selected some join clauses for remote use but also wants them
+        * rechecked locally).
+        */
+       scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rte->relid,
+                                                                                               best_path,
+                                                                                               tlist, scan_clauses);
+
+       /* Copy cost data from Path to Plan; no need to make FDW do this */
+       copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
+
+       /*
+        * Replace any outer-relation variables with nestloop params in the qual
+        * and fdw_exprs expressions.  We do this last so that the FDW doesn't
+        * have to be involved.  (Note that parts of fdw_exprs could have come
+        * from join clauses, so doing this beforehand on the scan_clauses
+        * wouldn't work.)
+        */
+       if (best_path->path.param_info)
+       {
+               scan_plan->scan.plan.qual = (List *)
+                       replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
+               scan_plan->fdw_exprs = (List *)
+                       replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
+       }
 
-       /* Detect whether any system columns are requested from rel */
-       fsSystemCol = false;
+       /*
+        * Detect whether any system columns are requested from rel.  This is a
+        * bit of a kluge and might go away someday, so we intentionally leave it
+        * out of the API presented to FDWs.
+        */
+       scan_plan->fsSystemCol = false;
        for (i = rel->min_attr; i < 0; i++)
        {
                if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
                {
-                       fsSystemCol = true;
+                       scan_plan->fsSystemCol = true;
                        break;
                }
        }
 
-       scan_plan = make_foreignscan(tlist,
-                                                                scan_clauses,
-                                                                scan_relid,
-                                                                fsSystemCol,
-                                                                best_path->fdwplan);
-
-       copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
-
        return scan_plan;
 }
 
@@ -1878,15 +2028,6 @@ create_nestloop_plan(PlannerInfo *root,
        ListCell   *prev;
        ListCell   *next;
 
-       /*
-        * If the inner path is parameterized, it might have already used some of
-        * the join quals, in which case we don't have to check them again at the
-        * join node.  Remove any join quals that are redundant.
-        */
-       joinrestrictclauses =
-               select_nonredundant_join_clauses(joinrestrictclauses,
-                                                                                best_path->innerjoinpath->param_clauses);
-
        /* Sort join qual clauses into best execution order */
        joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
 
@@ -1904,6 +2045,15 @@ create_nestloop_plan(PlannerInfo *root,
                otherclauses = NIL;
        }
 
+       /* Replace any outer-relation variables with nestloop params */
+       if (best_path->path.param_info)
+       {
+               joinclauses = (List *)
+                       replace_nestloop_params(root, (Node *) joinclauses);
+               otherclauses = (List *)
+                       replace_nestloop_params(root, (Node *) otherclauses);
+       }
+
        /*
         * Identify any nestloop parameters that should be supplied by this join
         * node, and move them from root->curOuterParams to the nestParams list.
@@ -1927,7 +2077,7 @@ create_nestloop_plan(PlannerInfo *root,
                                 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
                                                         outerrelids) &&
                                 bms_is_subset(find_placeholder_info(root,
-                                                                                                        (PlaceHolderVar *) nlp->paramval,
+                                                                                       (PlaceHolderVar *) nlp->paramval,
                                                                                                         false)->ph_eval_at,
                                                           outerrelids))
                {
@@ -2000,6 +2150,18 @@ create_mergejoin_plan(PlannerInfo *root,
        mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
        joinclauses = list_difference(joinclauses, mergeclauses);
 
+       /*
+        * Replace any outer-relation variables with nestloop params.  There
+        * should not be any in the mergeclauses.
+        */
+       if (best_path->jpath.path.param_info)
+       {
+               joinclauses = (List *)
+                       replace_nestloop_params(root, (Node *) joinclauses);
+               otherclauses = (List *)
+                       replace_nestloop_params(root, (Node *) otherclauses);
+       }
+
        /*
         * Rearrange mergeclauses, if needed, so that the outer variable is always
         * on the left; mark the mergeclause restrictinfos with correct
@@ -2278,6 +2440,18 @@ create_hashjoin_plan(PlannerInfo *root,
        hashclauses = get_actual_clauses(best_path->path_hashclauses);
        joinclauses = list_difference(joinclauses, hashclauses);
 
+       /*
+        * Replace any outer-relation variables with nestloop params.  There
+        * should not be any in the hashclauses.
+        */
+       if (best_path->jpath.path.param_info)
+       {
+               joinclauses = (List *)
+                       replace_nestloop_params(root, (Node *) joinclauses);
+               otherclauses = (List *)
+                       replace_nestloop_params(root, (Node *) otherclauses);
+       }
+
        /*
         * Rearrange hashclauses, if needed, so that the outer variable is always
         * on the left.
@@ -2421,9 +2595,9 @@ replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
 
                /*
                 * If not to be replaced, just return the PlaceHolderVar unmodified.
-                * We use bms_overlap as a cheap/quick test to see if the PHV might
-                * be evaluated in the outer rels, and then grab its PlaceHolderInfo
-                * to tell for sure.
+                * We use bms_overlap as a cheap/quick test to see if the PHV might be
+                * evaluated in the outer rels, and then grab its PlaceHolderInfo to
+                * tell for sure.
                 */
                if (!bms_overlap(phv->phrels, root->curOuterRels))
                        return node;
@@ -2456,6 +2630,92 @@ replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
                                                                   (void *) root);
 }
 
+/*
+ * process_subquery_nestloop_params
+ *       Handle params of a parameterized subquery that need to be fed
+ *       from an outer nestloop.
+ *
+ * Currently, that would be *all* params that a subquery in FROM has demanded
+ * from the current query level, since they must be LATERAL references.
+ *
+ * The subplan's references to the outer variables are already represented
+ * as PARAM_EXEC Params, so we need not modify the subplan here.  What we
+ * do need to do is add entries to root->curOuterParams to signal the parent
+ * nestloop plan node that it must provide these values.
+ */
+static void
+process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
+{
+       ListCell   *ppl;
+
+       foreach(ppl, subplan_params)
+       {
+               PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
+
+               if (IsA(pitem->item, Var))
+               {
+                       Var                *var = (Var *) pitem->item;
+                       NestLoopParam *nlp;
+                       ListCell   *lc;
+
+                       /* If not from a nestloop outer rel, complain */
+                       if (!bms_is_member(var->varno, root->curOuterRels))
+                               elog(ERROR, "non-LATERAL parameter required by subquery");
+                       /* Is this param already listed in root->curOuterParams? */
+                       foreach(lc, root->curOuterParams)
+                       {
+                               nlp = (NestLoopParam *) lfirst(lc);
+                               if (nlp->paramno == pitem->paramId)
+                               {
+                                       Assert(equal(var, nlp->paramval));
+                                       /* Present, so nothing to do */
+                                       break;
+                               }
+                       }
+                       if (lc == NULL)
+                       {
+                               /* No, so add it */
+                               nlp = makeNode(NestLoopParam);
+                               nlp->paramno = pitem->paramId;
+                               nlp->paramval = copyObject(var);
+                               root->curOuterParams = lappend(root->curOuterParams, nlp);
+                       }
+               }
+               else if (IsA(pitem->item, PlaceHolderVar))
+               {
+                       PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
+                       NestLoopParam *nlp;
+                       ListCell   *lc;
+
+                       /* If not from a nestloop outer rel, complain */
+                       if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
+                                                          root->curOuterRels))
+                               elog(ERROR, "non-LATERAL parameter required by subquery");
+                       /* Is this param already listed in root->curOuterParams? */
+                       foreach(lc, root->curOuterParams)
+                       {
+                               nlp = (NestLoopParam *) lfirst(lc);
+                               if (nlp->paramno == pitem->paramId)
+                               {
+                                       Assert(equal(phv, nlp->paramval));
+                                       /* Present, so nothing to do */
+                                       break;
+                               }
+                       }
+                       if (lc == NULL)
+                       {
+                               /* No, so add it */
+                               nlp = makeNode(NestLoopParam);
+                               nlp->paramno = pitem->paramId;
+                               nlp->paramval = copyObject(phv);
+                               root->curOuterParams = lappend(root->curOuterParams, nlp);
+                       }
+               }
+               else
+                       elog(ERROR, "unexpected type of subquery parameter");
+       }
+}
+
 /*
  * fix_indexqual_references
  *       Adjust indexqual clauses to the form the executor's indexqual
@@ -2510,7 +2770,7 @@ fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
 
                        /*
                         * Check to see if the indexkey is on the right; if so, commute
-                        * the clause.  The indexkey should be the side that refers to
+                        * the clause.  The indexkey should be the side that refers to
                         * (only) the base relation.
                         */
                        if (!bms_equal(rinfo->left_relids, index->rel->relids))
@@ -3181,24 +3441,26 @@ make_worktablescan(List *qptlist,
        return node;
 }
 
-static ForeignScan *
+ForeignScan *
 make_foreignscan(List *qptlist,
                                 List *qpqual,
                                 Index scanrelid,
-                                bool fsSystemCol,
-                                FdwPlan *fdwplan)
+                                List *fdw_exprs,
+                                List *fdw_private)
 {
        ForeignScan *node = makeNode(ForeignScan);
        Plan       *plan = &node->scan.plan;
 
-       /* cost should be inserted by caller */
+       /* cost will be filled in by create_foreignscan_plan */
        plan->targetlist = qptlist;
        plan->qual = qpqual;
        plan->lefttree = NULL;
        plan->righttree = NULL;
        node->scan.scanrelid = scanrelid;
-       node->fsSystemCol = fsSystemCol;
-       node->fdwplan = fdwplan;
+       node->fdw_exprs = fdw_exprs;
+       node->fdw_private = fdw_private;
+       /* fsSystemCol will be filled in by create_foreignscan_plan */
+       node->fsSystemCol = false;
 
        return node;
 }
@@ -3488,55 +3750,6 @@ make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
        return node;
 }
 
-/*
- * add_sort_column --- utility subroutine for building sort info arrays
- *
- * We need this routine because the same column might be selected more than
- * once as a sort key column; if so, the extra mentions are redundant.
- *
- * Caller is assumed to have allocated the arrays large enough for the
- * max possible number of columns.     Return value is the new column count.
- */
-static int
-add_sort_column(AttrNumber colIdx, Oid sortOp, Oid coll, bool nulls_first,
-                               int numCols, AttrNumber *sortColIdx,
-                               Oid *sortOperators, Oid *collations, bool *nullsFirst)
-{
-       int                     i;
-
-       Assert(OidIsValid(sortOp));
-
-       for (i = 0; i < numCols; i++)
-       {
-               /*
-                * Note: we check sortOp because it's conceivable that "ORDER BY foo
-                * USING <, foo USING <<<" is not redundant, if <<< distinguishes
-                * values that < considers equal.  We need not check nulls_first
-                * however because a lower-order column with the same sortop but
-                * opposite nulls direction is redundant.
-                *
-                * We could probably consider sort keys with the same sortop and
-                * different collations to be redundant too, but for the moment treat
-                * them as not redundant.  This will be needed if we ever support
-                * collations with different notions of equality.
-                */
-               if (sortColIdx[i] == colIdx &&
-                       sortOperators[numCols] == sortOp &&
-                       collations[numCols] == coll)
-               {
-                       /* Already sorting by this col, so extra sort key is useless */
-                       return numCols;
-               }
-       }
-
-       /* Add the column */
-       sortColIdx[numCols] = colIdx;
-       sortOperators[numCols] = sortOp;
-       collations[numCols] = coll;
-       nullsFirst[numCols] = nulls_first;
-       return numCols + 1;
-}
-
 /*
  * prepare_sort_from_pathkeys
  *       Prepare to sort according to given pathkeys
@@ -3546,8 +3759,10 @@ add_sort_column(AttrNumber colIdx, Oid sortOp, Oid coll, bool nulls_first,
  * plan targetlist if needed to add resjunk sort columns.
  *
  * Input parameters:
- *       'lefttree' is the node which yields input tuples
+ *       'lefttree' is the plan node which yields input tuples
  *       'pathkeys' is the list of pathkeys by which the result is to be sorted
+ *       'relids' identifies the child relation being sorted, if any
+ *       'reqColIdx' is NULL or an array of required sort key column numbers
  *       'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
  *
  * We must convert the pathkey information into arrays of sort key column
@@ -3555,6 +3770,14 @@ add_sort_column(AttrNumber colIdx, Oid sortOp, Oid coll, bool nulls_first,
  * which is the representation the executor wants.     These are returned into
  * the output parameters *p_numsortkeys etc.
  *
+ * When looking for matches to an EquivalenceClass's members, we will only
+ * consider child EC members if they match 'relids'.  This protects against
+ * possible incorrect matches to child expressions that contain no Vars.
+ *
+ * If reqColIdx isn't NULL then it contains sort key column numbers that
+ * we should match.  This is used when making child plans for a MergeAppend;
+ * it's an error if we can't match the columns.
+ *
  * If the pathkeys include expressions that aren't simple Vars, we will
  * usually need to add resjunk items to the input plan's targetlist to
  * compute these expressions, since the Sort/MergeAppend node itself won't
@@ -3569,6 +3792,8 @@ add_sort_column(AttrNumber colIdx, Oid sortOp, Oid coll, bool nulls_first,
  */
 static Plan *
 prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
+                                                  Relids relids,
+                                                  const AttrNumber *reqColIdx,
                                                   bool adjust_tlist_in_place,
                                                   int *p_numsortkeys,
                                                   AttrNumber **p_sortColIdx,
@@ -3599,6 +3824,7 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
        {
                PathKey    *pathkey = (PathKey *) lfirst(i);
                EquivalenceClass *ec = pathkey->pk_eclass;
+               EquivalenceMember *em;
                TargetEntry *tle = NULL;
                Oid                     pk_datatype = InvalidOid;
                Oid                     sortop;
@@ -3618,16 +3844,40 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
                        Assert(list_length(ec->ec_members) == 1);
                        pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
                }
+               else if (reqColIdx != NULL)
+               {
+                       /*
+                        * If we are given a sort column number to match, only consider
+                        * the single TLE at that position.  It's possible that there is
+                        * no such TLE, in which case fall through and generate a resjunk
+                        * targetentry (we assume this must have happened in the parent
+                        * plan as well).  If there is a TLE but it doesn't match the
+                        * pathkey's EC, we do the same, which is probably the wrong thing
+                        * but we'll leave it to caller to complain about the mismatch.
+                        */
+                       tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
+                       if (tle)
+                       {
+                               em = find_ec_member_for_tle(ec, tle, relids);
+                               if (em)
+                               {
+                                       /* found expr at right place in tlist */
+                                       pk_datatype = em->em_datatype;
+                               }
+                               else
+                                       tle = NULL;
+                       }
+               }
                else
                {
                        /*
                         * Otherwise, we can sort by any non-constant expression listed in
-                        * the pathkey's EquivalenceClass.  For now, we take the first one
-                        * that corresponds to an available item in the tlist.  If there
-                        * isn't any, use the first one that is an expression in the
-                        * input's vars.  (The non-const restriction only matters if the
-                        * EC is below_outer_join; but if it isn't, it won't contain
-                        * consts anyway, else we'd have discarded the pathkey as
+                        * the pathkey's EquivalenceClass.  For now, we take the first
+                        * tlist item found in the EC. If there's no match, we'll generate
+                        * a resjunk entry using the first EC member that is an expression
+                        * in the input's vars.  (The non-const restriction only matters
+                        * if the EC is below_outer_join; but if it isn't, it won't
+                        * contain consts anyway, else we'd have discarded the pathkey as
                         * redundant.)
                         *
                         * XXX if we have a choice, is there any way of figuring out which
@@ -3636,9 +3886,36 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
                         * in the same equivalence class...)  Not clear that we ever will
                         * have an interesting choice in practice, so it may not matter.
                         */
+                       foreach(j, tlist)
+                       {
+                               tle = (TargetEntry *) lfirst(j);
+                               em = find_ec_member_for_tle(ec, tle, relids);
+                               if (em)
+                               {
+                                       /* found expr already in tlist */
+                                       pk_datatype = em->em_datatype;
+                                       break;
+                               }
+                               tle = NULL;
+                       }
+               }
+
+               if (!tle)
+               {
+                       /*
+                        * No matching tlist item; look for a computable expression. Note
+                        * that we treat Aggrefs as if they were variables; this is
+                        * necessary when attempting to sort the output from an Agg node
+                        * for use in a WindowFunc (since grouping_planner will have
+                        * treated the Aggrefs as variables, too).
+                        */
+                       Expr       *sortexpr = NULL;
+
                        foreach(j, ec->ec_members)
                        {
                                EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
+                               List       *exprvars;
+                               ListCell   *k;
 
                                /*
                                 * We shouldn't be trying to sort by an equivalence class that
@@ -3648,91 +3925,57 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
                                if (em->em_is_const)
                                        continue;
 
-                               tle = tlist_member((Node *) em->em_expr, tlist);
-                               if (tle)
-                               {
-                                       pk_datatype = em->em_datatype;
-                                       break;          /* found expr already in tlist */
-                               }
-
                                /*
-                                * We can also use it if the pathkey expression is a relabel
-                                * of the tlist entry, or vice versa.  This is needed for
-                                * binary-compatible cases (cf. make_pathkey_from_sortinfo).
-                                * We prefer an exact match, though, so we do the basic search
-                                * first.
+                                * Ignore child members unless they match the rel being
+                                * sorted.
                                 */
-                               tle = tlist_member_ignore_relabel((Node *) em->em_expr, tlist);
-                               if (tle)
+                               if (em->em_is_child &&
+                                       !bms_equal(em->em_relids, relids))
+                                       continue;
+
+                               sortexpr = em->em_expr;
+                               exprvars = pull_var_clause((Node *) sortexpr,
+                                                                                  PVC_INCLUDE_AGGREGATES,
+                                                                                  PVC_INCLUDE_PLACEHOLDERS);
+                               foreach(k, exprvars)
+                               {
+                                       if (!tlist_member_ignore_relabel(lfirst(k), tlist))
+                                               break;
+                               }
+                               list_free(exprvars);
+                               if (!k)
                                {
                                        pk_datatype = em->em_datatype;
-                                       break;          /* found expr already in tlist */
+                                       break;          /* found usable expression */
                                }
                        }
+                       if (!j)
+                               elog(ERROR, "could not find pathkey item to sort");
 
-                       if (!tle)
+                       /*
+                        * Do we need to insert a Result node?
+                        */
+                       if (!adjust_tlist_in_place &&
+                               !is_projection_capable_plan(lefttree))
                        {
-                               /*
-                                * No matching tlist item; look for a computable expression.
-                                * Note that we treat Aggrefs as if they were variables; this
-                                * is necessary when attempting to sort the output from an Agg
-                                * node for use in a WindowFunc (since grouping_planner will
-                                * have treated the Aggrefs as variables, too).
-                                */
-                               Expr       *sortexpr = NULL;
-
-                               foreach(j, ec->ec_members)
-                               {
-                                       EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
-                                       List       *exprvars;
-                                       ListCell   *k;
-
-                                       if (em->em_is_const)
-                                               continue;
-                                       sortexpr = em->em_expr;
-                                       exprvars = pull_var_clause((Node *) sortexpr,
-                                                                                          PVC_INCLUDE_AGGREGATES,
-                                                                                          PVC_INCLUDE_PLACEHOLDERS);
-                                       foreach(k, exprvars)
-                                       {
-                                               if (!tlist_member_ignore_relabel(lfirst(k), tlist))
-                                                       break;
-                                       }
-                                       list_free(exprvars);
-                                       if (!k)
-                                       {
-                                               pk_datatype = em->em_datatype;
-                                               break;  /* found usable expression */
-                                       }
-                               }
-                               if (!j)
-                                       elog(ERROR, "could not find pathkey item to sort");
-
-                               /*
-                                * Do we need to insert a Result node?
-                                */
-                               if (!adjust_tlist_in_place &&
-                                       !is_projection_capable_plan(lefttree))
-                               {
-                                       /* copy needed so we don't modify input's tlist below */
-                                       tlist = copyObject(tlist);
-                                       lefttree = (Plan *) make_result(root, tlist, NULL,
-                                                                                                       lefttree);
-                               }
+                               /* copy needed so we don't modify input's tlist below */
+                               tlist = copyObject(tlist);
+                               lefttree = (Plan *) make_result(root, tlist, NULL,
+                                                                                               lefttree);
+                       }
 
-                               /* Don't bother testing is_projection_capable_plan again */
-                               adjust_tlist_in_place = true;
+                       /* Don't bother testing is_projection_capable_plan again */
+                       adjust_tlist_in_place = true;
 
-                               /*
-                                * Add resjunk entry to input's tlist
-                                */
-                               tle = makeTargetEntry(sortexpr,
-                                                                         list_length(tlist) + 1,
-                                                                         NULL,
-                                                                         true);
-                               tlist = lappend(tlist, tle);
-                               lefttree->targetlist = tlist;   /* just in case NIL before */
-                       }
+                       /*
+                        * Add resjunk entry to input's tlist
+                        */
+                       tle = makeTargetEntry(sortexpr,
+                                                                 list_length(tlist) + 1,
+                                                                 NULL,
+                                                                 true);
+                       tlist = lappend(tlist, tle);
+                       lefttree->targetlist = tlist;           /* just in case NIL before */
                }
 
                /*
@@ -3748,23 +3991,14 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
                                 pathkey->pk_strategy, pk_datatype, pk_datatype,
                                 pathkey->pk_opfamily);
 
-               /*
-                * The column might already be selected as a sort key, if the pathkeys
-                * contain duplicate entries.  (This can happen in scenarios where
-                * multiple mergejoinable clauses mention the same var, for example.)
-                * So enter it only once in the sort arrays.
-                */
-               numsortkeys = add_sort_column(tle->resno,
-                                                                         sortop,
-                                                                         pathkey->pk_eclass->ec_collation,
-                                                                         pathkey->pk_nulls_first,
-                                                                         numsortkeys,
-                                                                         sortColIdx, sortOperators,
-                                                                         collations, nullsFirst);
+               /* Add the column to the sort arrays */
+               sortColIdx[numsortkeys] = tle->resno;
+               sortOperators[numsortkeys] = sortop;
+               collations[numsortkeys] = ec->ec_collation;
+               nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
+               numsortkeys++;
        }
 
-       Assert(numsortkeys > 0);
-
        /* Return results */
        *p_numsortkeys = numsortkeys;
        *p_sortColIdx = sortColIdx;
@@ -3775,6 +4009,56 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
        return lefttree;
 }
 
+/*
+ * find_ec_member_for_tle
+ *             Locate an EquivalenceClass member matching the given TLE, if any
+ *
+ * Child EC members are ignored unless they match 'relids'.
+ */
+static EquivalenceMember *
+find_ec_member_for_tle(EquivalenceClass *ec,
+                                          TargetEntry *tle,
+                                          Relids relids)
+{
+       Expr       *tlexpr;
+       ListCell   *lc;
+
+       /* We ignore binary-compatible relabeling on both ends */
+       tlexpr = tle->expr;
+       while (tlexpr && IsA(tlexpr, RelabelType))
+               tlexpr = ((RelabelType *) tlexpr)->arg;
+
+       foreach(lc, ec->ec_members)
+       {
+               EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
+               Expr       *emexpr;
+
+               /*
+                * We shouldn't be trying to sort by an equivalence class that
+                * contains a constant, so no need to consider such cases any further.
+                */
+               if (em->em_is_const)
+                       continue;
+
+               /*
+                * Ignore child members unless they match the rel being sorted.
+                */
+               if (em->em_is_child &&
+                       !bms_equal(em->em_relids, relids))
+                       continue;
+
+               /* Match if same expression (after stripping relabel) */
+               emexpr = em->em_expr;
+               while (emexpr && IsA(emexpr, RelabelType))
+                       emexpr = ((RelabelType *) emexpr)->arg;
+
+               if (equal(emexpr, tlexpr))
+                       return em;
+       }
+
+       return NULL;
+}
+
 /*
  * make_sort_from_pathkeys
  *       Create sort plan to sort according to given pathkeys
@@ -3796,6 +4080,8 @@ make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
 
        /* Compute sort column info, and adjust lefttree as needed */
        lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys,
+                                                                                 NULL,
+                                                                                 NULL,
                                                                                  false,
                                                                                  &numsortkeys,
                                                                                  &sortColIdx,
@@ -3827,9 +4113,7 @@ make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
        Oid                *collations;
        bool       *nullsFirst;
 
-       /*
-        * We will need at most list_length(sortcls) sort columns; possibly less
-        */
+       /* Convert list-ish representation to arrays wanted by executor */
        numsortkeys = list_length(sortcls);
        sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
        sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
@@ -3837,27 +4121,18 @@ make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
        nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
 
        numsortkeys = 0;
-
        foreach(l, sortcls)
        {
                SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
                TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
 
-               /*
-                * Check for the possibility of duplicate order-by clauses --- the
-                * parser should have removed 'em, but no point in sorting
-                * redundantly.
-                */
-               numsortkeys = add_sort_column(tle->resno, sortcl->sortop,
-                                                                         exprCollation((Node *) tle->expr),
-                                                                         sortcl->nulls_first,
-                                                                         numsortkeys,
-                                                                         sortColIdx, sortOperators,
-                                                                         collations, nullsFirst);
+               sortColIdx[numsortkeys] = tle->resno;
+               sortOperators[numsortkeys] = sortcl->sortop;
+               collations[numsortkeys] = exprCollation((Node *) tle->expr);
+               nullsFirst[numsortkeys] = sortcl->nulls_first;
+               numsortkeys++;
        }
 
-       Assert(numsortkeys > 0);
-
        return make_sort(root, lefttree, numsortkeys,
                                         sortColIdx, sortOperators, collations,
                                         nullsFirst, -1.0);
@@ -3883,7 +4158,6 @@ make_sort_from_groupcols(PlannerInfo *root,
                                                 Plan *lefttree)
 {
        List       *sub_tlist = lefttree->targetlist;
-       int                     grpno = 0;
        ListCell   *l;
        int                     numsortkeys;
        AttrNumber *sortColIdx;
@@ -3891,9 +4165,7 @@ make_sort_from_groupcols(PlannerInfo *root,
        Oid                *collations;
        bool       *nullsFirst;
 
-       /*
-        * We will need at most list_length(groupcls) sort columns; possibly less
-        */
+       /* Convert list-ish representation to arrays wanted by executor */
        numsortkeys = list_length(groupcls);
        sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
        sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
@@ -3901,28 +4173,18 @@ make_sort_from_groupcols(PlannerInfo *root,
        nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
 
        numsortkeys = 0;
-
        foreach(l, groupcls)
        {
                SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
-               TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
+               TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
 
-               /*
-                * Check for the possibility of duplicate group-by clauses --- the
-                * parser should have removed 'em, but no point in sorting
-                * redundantly.
-                */
-               numsortkeys = add_sort_column(tle->resno, grpcl->sortop,
-                                                                         exprCollation((Node *) tle->expr),
-                                                                         grpcl->nulls_first,
-                                                                         numsortkeys,
-                                                                         sortColIdx, sortOperators,
-                                                                         collations, nullsFirst);
-               grpno++;
+               sortColIdx[numsortkeys] = tle->resno;
+               sortOperators[numsortkeys] = grpcl->sortop;
+               collations[numsortkeys] = exprCollation((Node *) tle->expr);
+               nullsFirst[numsortkeys] = grpcl->nulls_first;
+               numsortkeys++;
        }
 
-       Assert(numsortkeys > 0);
-
        return make_sort(root, lefttree, numsortkeys,
                                         sortColIdx, sortOperators, collations,
                                         nullsFirst, -1.0);
@@ -4022,8 +4284,8 @@ make_agg(PlannerInfo *root, List *tlist, List *qual,
         * anything for Aggref nodes; this is okay since they are really
         * comparable to Vars.
         *
-        * See notes in grouping_planner about why only make_agg, make_windowagg
-        * and make_group worry about tlist eval cost.
+        * See notes in add_tlist_costs_to_plan about why only make_agg,
+        * make_windowagg and make_group worry about tlist eval cost.
         */
        if (qual)
        {
@@ -4032,10 +4294,7 @@ make_agg(PlannerInfo *root, List *tlist, List *qual,
                plan->total_cost += qual_cost.startup;
                plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
        }
-       cost_qual_eval(&qual_cost, tlist, root);
-       plan->startup_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
+       add_tlist_costs_to_plan(root, plan, tlist);
 
        plan->qual = qual;
        plan->targetlist = tlist;
@@ -4056,7 +4315,6 @@ make_windowagg(PlannerInfo *root, List *tlist,
        WindowAgg  *node = makeNode(WindowAgg);
        Plan       *plan = &node->plan;
        Path            windowagg_path; /* dummy for result of cost_windowagg */
-       QualCost        qual_cost;
 
        node->winref = winref;
        node->partNumCols = partNumCols;
@@ -4081,13 +4339,10 @@ make_windowagg(PlannerInfo *root, List *tlist,
        /*
         * We also need to account for the cost of evaluation of the tlist.
         *
-        * See notes in grouping_planner about why only make_agg, make_windowagg
-        * and make_group worry about tlist eval cost.
+        * See notes in add_tlist_costs_to_plan about why only make_agg,
+        * make_windowagg and make_group worry about tlist eval cost.
         */
-       cost_qual_eval(&qual_cost, tlist, root);
-       plan->startup_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
+       add_tlist_costs_to_plan(root, plan, tlist);
 
        plan->targetlist = tlist;
        plan->lefttree = lefttree;
@@ -4138,8 +4393,8 @@ make_group(PlannerInfo *root,
         * lower plan level and will only be copied by the Group node. Worth
         * fixing?
         *
-        * See notes in grouping_planner about why only make_agg, make_windowagg
-        * and make_group worry about tlist eval cost.
+        * See notes in add_tlist_costs_to_plan about why only make_agg,
+        * make_windowagg and make_group worry about tlist eval cost.
         */
        if (qual)
        {
@@ -4148,10 +4403,7 @@ make_group(PlannerInfo *root,
                plan->total_cost += qual_cost.startup;
                plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
        }
-       cost_qual_eval(&qual_cost, tlist, root);
-       plan->startup_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.startup;
-       plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
+       add_tlist_costs_to_plan(root, plan, tlist);
 
        plan->qual = qual;
        plan->targetlist = tlist;
@@ -4482,16 +4734,8 @@ make_modifytable(CmdType operation, bool canSetTag,
        node->plan.lefttree = NULL;
        node->plan.righttree = NULL;
        node->plan.qual = NIL;
-
-       /*
-        * Set up the visible plan targetlist as being the same as the first
-        * RETURNING list.      This is for the use of EXPLAIN; the executor won't pay
-        * any attention to the targetlist.
-        */
-       if (returningLists)
-               node->plan.targetlist = copyObject(linitial(returningLists));
-       else
-               node->plan.targetlist = NIL;
+       /* setrefs.c will fill in the targetlist, if needed */
+       node->plan.targetlist = NIL;
 
        node->operation = operation;
        node->canSetTag = canSetTag;