diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c
index 949844d979108433f8e92527ff16646017230a61..01a63c823e22e638e45e30cbd0015e5dbb5a19c6 100644
--- a/src/backend/commands/copy.c
+++ b/src/backend/commands/copy.c
@@ -1123,7 +1123,7 @@ ProcessCopyOptions(ParseState *pstate,
 			if (defel->arg && IsA(defel->arg, A_Star))
 				cstate->force_quote_all = true;
 			else if (defel->arg && IsA(defel->arg, List))
-				cstate->force_quote = (List *) defel->arg;
+				cstate->force_quote = castNode(List, defel->arg);
 			else
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index c2f03b73f4a85f8a7f846aca9bdaa9332b8a0faa..71b24a079cddf6659cdae4c1a2a723fafcd7f9d8 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -111,8 +111,7 @@ exprType(const Node *expr)
 
 					if (!qtree || !IsA(qtree, Query))
 						elog(ERROR, "cannot get type for untransformed sublink");
-					tent = (TargetEntry *) linitial(qtree->targetList);
-					Assert(IsA(tent, TargetEntry));
+					tent = castNode(TargetEntry, linitial(qtree->targetList));
 					Assert(!tent->resjunk);
 					type = exprType((Node *) tent->expr);
 					if (sublink->subLinkType == ARRAY_SUBLINK)
@@ -322,8 +321,7 @@ exprTypmod(const Node *expr)
 
 					if (!qtree || !IsA(qtree, Query))
 						elog(ERROR, "cannot get type for untransformed sublink");
-					tent = (TargetEntry *) linitial(qtree->targetList);
-					Assert(IsA(tent, TargetEntry));
+					tent = castNode(TargetEntry, linitial(qtree->targetList));
 					Assert(!tent->resjunk);
 					return exprTypmod((Node *) tent->expr);
 					/* note we don't need to care if it's an array */
@@ -381,9 +379,8 @@ exprTypmod(const Node *expr)
 					return -1;	/* no point in trying harder */
 				foreach(arg, cexpr->args)
 				{
-					CaseWhen   *w = (CaseWhen *) lfirst(arg);
+					CaseWhen   *w = castNode(CaseWhen, lfirst(arg));
 
-					Assert(IsA(w, CaseWhen));
 					if (exprType((Node *) w->result) != casetype)
 						return -1;
 					if (exprTypmod((Node *) w->result) != typmod)
@@ -809,8 +806,7 @@ exprCollation(const Node *expr)
 
 					if (!qtree || !IsA(qtree, Query))
 						elog(ERROR, "cannot get collation for untransformed sublink");
-					tent = (TargetEntry *) linitial(qtree->targetList);
-					Assert(IsA(tent, TargetEntry));
+					tent = castNode(TargetEntry, linitial(qtree->targetList));
 					Assert(!tent->resjunk);
 					coll = exprCollation((Node *) tent->expr);
 					/* collation doesn't change if it's converted to array */
@@ -1052,8 +1048,7 @@ exprSetCollation(Node *expr, Oid collation)
 
 					if (!qtree || !IsA(qtree, Query))
 						elog(ERROR, "cannot set collation for untransformed sublink");
-					tent = (TargetEntry *) linitial(qtree->targetList);
-					Assert(IsA(tent, TargetEntry));
+					tent = castNode(TargetEntry, linitial(qtree->targetList));
 					Assert(!tent->resjunk);
 					Assert(collation == exprCollation((Node *) tent->expr));
 				}
@@ -2050,9 +2045,8 @@ expression_tree_walker(Node *node,
 				/* we assume walker doesn't care about CaseWhens, either */
 				foreach(temp, caseexpr->args)
 				{
-					CaseWhen   *when = (CaseWhen *) lfirst(temp);
+					CaseWhen   *when = castNode(CaseWhen, lfirst(temp));
 
-					Assert(IsA(when, CaseWhen));
 					if (walker(when->expr, context))
 						return true;
 					if (walker(when->result, context))
@@ -3261,9 +3255,8 @@ raw_expression_tree_walker(Node *node,
 				/* we assume walker doesn't care about CaseWhens, either */
 				foreach(temp, caseexpr->args)
 				{
-					CaseWhen   *when = (CaseWhen *) lfirst(temp);
+					CaseWhen   *when = castNode(CaseWhen, lfirst(temp));
 
-					Assert(IsA(when, CaseWhen));
 					if (walker(when->expr, context))
 						return true;
 					if (walker(when->result, context))
@@ -3735,9 +3728,8 @@ planstate_walk_subplans(List *plans,
 
 	foreach(lc, plans)
 	{
-		SubPlanState *sps = (SubPlanState *) lfirst(lc);
+		SubPlanState *sps = castNode(SubPlanState, lfirst(lc));
 
-		Assert(IsA(sps, SubPlanState));
 		if (walker(sps->planstate, context))
 			return true;
 	}
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index eeacf815e3517dc1e15f8898bc6ae101ddfca018..633b5c1608d0d649431d4bb18150b6a3610f9764 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -2382,8 +2382,8 @@ subquery_is_pushdown_safe(Query *subquery, Query *topquery,
 		if (subquery->setOperations != NULL)
 			return false;
 		/* Check whether setop component output types match top level */
-		topop = (SetOperationStmt *) topquery->setOperations;
-		Assert(topop && IsA(topop, SetOperationStmt));
+		topop = castNode(SetOperationStmt, topquery->setOperations);
+		Assert(topop);
 		compare_tlist_datatypes(subquery->targetList,
 								topop->colTypes,
 								safetyInfo);
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index d01630f8dba7f2e1a0cc6235153b3cdc50f8d649..c138f57ebb4416cd8ff723be95aeaee67799baf2 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -682,9 +682,8 @@ extract_nonindex_conditions(List *qual_clauses, List *indexquals)
 
 	foreach(lc, qual_clauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
 
-		Assert(IsA(rinfo, RestrictInfo));
 		if (rinfo->pseudoconstant)
 			continue;			/* we may drop pseudoconstants here */
 		if (list_member_ptr(indexquals, rinfo))
@@ -1804,12 +1803,10 @@ cost_windowagg(Path *path, PlannerInfo *root,
 	 */
 	foreach(lc, windowFuncs)
 	{
-		WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
+		WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc));
 		Cost		wfunccost;
 		QualCost	argcosts;
 
-		Assert(IsA(wfunc, WindowFunc));
-
 		wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
 
 		/* also add the input expressions' cost to per-input-row costs */
@@ -2843,11 +2840,9 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path,
 		innerbucketsize = 1.0;
 		foreach(hcl, hashclauses)
 		{
-			RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
+			RestrictInfo *restrictinfo = castNode(RestrictInfo, lfirst(hcl));
 			Selectivity thisbucketsize;
 
-			Assert(IsA(restrictinfo, RestrictInfo));
-
 			/*
 			 * First we have to figure out which side of the hashjoin clause
 			 * is the inner side.
@@ -3537,9 +3532,8 @@ compute_semi_anti_join_factors(PlannerInfo *root,
 		joinquals = NIL;
 		foreach(l, restrictlist)
 		{
-			RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+			RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
-			Assert(IsA(rinfo, RestrictInfo));
 			if (!rinfo->is_pushed_down)
 				joinquals = lappend(joinquals, rinfo);
 		}
@@ -3970,9 +3964,8 @@ calc_joinrel_size_estimate(PlannerInfo *root,
 		/* Grovel through the clauses to separate into two lists */
 		foreach(l, restrictlist)
 		{
-			RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+			RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
-			Assert(IsA(rinfo, RestrictInfo));
 			if (rinfo->is_pushed_down)
 				pushedquals = lappend(pushedquals, rinfo);
 			else
@@ -4345,11 +4338,10 @@ set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
 	 */
 	foreach(lc, subroot->parse->targetList)
 	{
-		TargetEntry *te = (TargetEntry *) lfirst(lc);
+		TargetEntry *te = castNode(TargetEntry, lfirst(lc));
 		Node	   *texpr = (Node *) te->expr;
 		int32		item_width = 0;
 
-		Assert(IsA(te, TargetEntry));
 		/* junk columns aren't visible to upper query */
 		if (te->resjunk)
 			continue;
diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c
index d92826bcfc9ebf2116a1d350174f5bfee4808e7f..9c069983d912b1679c7a4070a7668558a02b23a8 100644
--- a/src/backend/optimizer/path/indxpath.c
+++ b/src/backend/optimizer/path/indxpath.c
@@ -1273,12 +1273,11 @@ generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
 
 	foreach(lc, clauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
 		List	   *pathlist;
 		Path	   *bitmapqual;
 		ListCell   *j;
 
-		Assert(IsA(rinfo, RestrictInfo));
 		/* Ignore RestrictInfos that aren't ORs */
 		if (!restriction_is_or_clause(rinfo))
 			continue;
@@ -1310,10 +1309,10 @@ generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
 			}
 			else
 			{
+				RestrictInfo *rinfo = castNode(RestrictInfo, orarg);
 				List	   *orargs;
 
-				Assert(IsA(orarg, RestrictInfo));
-				Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
+				Assert(!restriction_is_or_clause(rinfo));
 				orargs = list_make1(orarg);
 
 				indlist = build_paths_for_OR(root, rel,
@@ -2174,9 +2173,8 @@ match_clauses_to_index(IndexOptInfo *index,
 
 	foreach(lc, clauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
 
-		Assert(IsA(rinfo, RestrictInfo));
 		match_clause_to_index(index, rinfo, clauseset);
 	}
 }
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index 6f3c20b33ff6ef35a4c5723cd3cb186196316525..0d0068360c128d61a0a64161a292837a29523630 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -1230,9 +1230,8 @@ restriction_is_constant_false(List *restrictlist, bool only_pushed_down)
 	 */
 	foreach(lc, restrictlist)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
 
-		Assert(IsA(rinfo, RestrictInfo));
 		if (only_pushed_down && !rinfo->is_pushed_down)
 			continue;
 
diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c
index 438baf1e61f2fc423f20cc8d09977658c039471d..ac63f7572b66a2f4ce1c5f9f3f896d2a9f25aaff 100644
--- a/src/backend/optimizer/plan/analyzejoins.c
+++ b/src/backend/optimizer/plan/analyzejoins.c
@@ -596,7 +596,7 @@ rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list)
 		 */
 		foreach(l, clause_list)
 		{
-			RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+			RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 			Oid			op;
 			Var		   *var;
 
@@ -608,8 +608,7 @@ rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list)
 			 * caller's mergejoinability test should have selected only
 			 * OpExprs.
 			 */
-			Assert(IsA(rinfo->clause, OpExpr));
-			op = ((OpExpr *) rinfo->clause)->opno;
+			op = castNode(OpExpr, rinfo->clause)->opno;
 
 			/* caller identified the inner side for us */
 			if (rinfo->outer_is_left)
@@ -782,9 +781,8 @@ query_is_distinct_for(Query *query, List *colnos, List *opids)
 	 */
 	if (query->setOperations)
 	{
-		SetOperationStmt *topop = (SetOperationStmt *) query->setOperations;
+		SetOperationStmt *topop = castNode(SetOperationStmt, query->setOperations);
 
-		Assert(IsA(topop, SetOperationStmt));
 		Assert(topop->op != SETOP_NONE);
 
 		if (!topop->all)
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 997bdcff2ea90f0dcc1e66b1e8346f9c2bb3652c..1e953b40d6f5dfafa53f4f1f851e6145608fbf07 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -508,8 +508,7 @@ create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
 	{
 		case T_IndexScan:
 		case T_IndexOnlyScan:
-			Assert(IsA(best_path, IndexPath));
-			scan_clauses = ((IndexPath *) best_path)->indexinfo->indrestrictinfo;
+			scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
 			break;
 		default:
 			scan_clauses = rel->baserestrictinfo;
@@ -2450,9 +2449,8 @@ create_indexscan_plan(PlannerInfo *root,
 	qpqual = NIL;
 	foreach(l, scan_clauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
-		Assert(IsA(rinfo, RestrictInfo));
 		if (rinfo->pseudoconstant)
 			continue;			/* we may drop pseudoconstants here */
 		if (list_member_ptr(indexquals, rinfo))
@@ -2608,10 +2606,9 @@ create_bitmap_scan_plan(PlannerInfo *root,
 	qpqual = NIL;
 	foreach(l, scan_clauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
+		RestrictInfo *rinfo = castNode(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))
@@ -2820,9 +2817,9 @@ create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
 		ListCell   *l;
 
 		/* Use the regular indexscan plan build machinery... */
-		iscan = (IndexScan *) create_indexscan_plan(root, ipath,
-													NIL, NIL, false);
-		Assert(IsA(iscan, IndexScan));
+		iscan = castNode(IndexScan,
+						 create_indexscan_plan(root, ipath,
+											   NIL, NIL, false));
 		/* then convert to a bitmap indexscan */
 		plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
 											  iscan->indexid,
@@ -3391,13 +3388,13 @@ create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
 	 * Invoke custom plan provider to create the Plan node represented by the
 	 * CustomPath.
 	 */
-	cplan = (CustomScan *) best_path->methods->PlanCustomPath(root,
-															  rel,
-															  best_path,
-															  tlist,
-															  scan_clauses,
-															  custom_plans);
-	Assert(IsA(cplan, CustomScan));
+	cplan = castNode(CustomScan,
+					 best_path->methods->PlanCustomPath(root,
+														rel,
+														best_path,
+														tlist,
+														scan_clauses,
+														custom_plans));
 
 	/*
 	 * Copy cost data from Path to Plan; no need to make custom-plan providers
@@ -3683,7 +3680,7 @@ create_mergejoin_plan(PlannerInfo *root,
 	i = 0;
 	foreach(lc, best_path->path_mergeclauses)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
 		EquivalenceClass *oeclass;
 		EquivalenceClass *ieclass;
 		PathKey    *opathkey;
@@ -3693,7 +3690,6 @@ create_mergejoin_plan(PlannerInfo *root,
 		ListCell   *l2;
 
 		/* fetch outer/inner eclass from mergeclause */
-		Assert(IsA(rinfo, RestrictInfo));
 		if (rinfo->outer_is_left)
 		{
 			oeclass = rinfo->left_ec;
@@ -4228,12 +4224,10 @@ fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
 
 	forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lcc));
 		int			indexcol = lfirst_int(lci);
 		Node	   *clause;
 
-		Assert(IsA(rinfo, RestrictInfo));
-
 		/*
 		 * Replace any outer-relation variables with nestloop params.
 		 *
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 3d33d469713cab64ccc8421453ae29ebab2d6a94..ca0ae7883e795b6845930b1bf53a8206cbe041d3 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -3963,9 +3963,8 @@ create_one_window_path(PlannerInfo *root,
 			window_target = copy_pathtarget(window_target);
 			foreach(lc2, wflists->windowFuncs[wc->winref])
 			{
-				WindowFunc *wfunc = (WindowFunc *) lfirst(lc2);
+				WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc2));
 
-				Assert(IsA(wfunc, WindowFunc));
 				add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
 				window_target->width += get_typavgwidth(wfunc->wintype, -1);
 			}
diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c
index be267b9da74a57d421e4896487f981abb768da50..07ddbcf37e9e46f5b452d89545f0b14247fd2348 100644
--- a/src/backend/optimizer/plan/setrefs.c
+++ b/src/backend/optimizer/plan/setrefs.c
@@ -224,11 +224,9 @@ set_plan_references(PlannerInfo *root, Plan *plan)
 	 */
 	foreach(lc, root->rowMarks)
 	{
-		PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
+		PlanRowMark *rc = castNode(PlanRowMark, lfirst(lc));
 		PlanRowMark *newrc;
 
-		Assert(IsA(rc, PlanRowMark));
-
 		/* flat copy is enough since all fields are scalars */
 		newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
 		memcpy(newrc, rc, sizeof(PlanRowMark));
diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c
index 7954c445dd91798ad2f3f59e745f34fe2db066e1..3eb2bb749e4a2c981e19101564fd26052ffcc406 100644
--- a/src/backend/optimizer/plan/subselect.c
+++ b/src/backend/optimizer/plan/subselect.c
@@ -433,9 +433,8 @@ get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
 	/* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
 	if (plan->targetlist)
 	{
-		TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist);
+		TargetEntry *tent = castNode(TargetEntry, linitial(plan->targetlist));
 
-		Assert(IsA(tent, TargetEntry));
 		if (!tent->resjunk)
 		{
 			*coltype = exprType((Node *) tent->expr);
@@ -601,14 +600,14 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
 				AlternativeSubPlan *asplan;
 
 				/* OK, convert to SubPlan format. */
-				hashplan = (SubPlan *) build_subplan(root, plan, subroot,
-													 plan_params,
-													 ANY_SUBLINK, 0,
-													 newtestexpr,
-													 false, true,
-												   best_path->parallel_safe);
+				hashplan = castNode(SubPlan,
+									build_subplan(root, plan, subroot,
+												  plan_params,
+												  ANY_SUBLINK, 0,
+												  newtestexpr,
+												  false, true,
+												  best_path->parallel_safe));
 				/* Check we got what we expected */
-				Assert(IsA(hashplan, SubPlan));
 				Assert(hashplan->parParam == NIL);
 				Assert(hashplan->useHashTable);
 				/* build_subplan won't have filled in paramIds */
diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c
index 6911177b68a7bd1b0bd8b0d767a58e8527074001..6c6ac8dc0aa27a26edfc9dfb6f623badea93ae9d 100644
--- a/src/backend/optimizer/prep/prepjointree.c
+++ b/src/backend/optimizer/prep/prepjointree.c
@@ -1748,10 +1748,9 @@ is_simple_union_all(Query *subquery)
 		elog(ERROR, "subquery is bogus");
 
 	/* Is it a set-operation query at all? */
-	topop = (SetOperationStmt *) subquery->setOperations;
+	topop = castNode(SetOperationStmt, subquery->setOperations);
 	if (!topop)
 		return false;
-	Assert(IsA(topop, SetOperationStmt));
 
 	/* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
 	if (subquery->sortClause ||
@@ -2323,8 +2322,8 @@ flatten_simple_union_all(PlannerInfo *root)
 	RangeTblRef *rtr;
 
 	/* Shouldn't be called unless query has setops */
-	topop = (SetOperationStmt *) parse->setOperations;
-	Assert(topop && IsA(topop, SetOperationStmt));
+	topop = castNode(SetOperationStmt, parse->setOperations);
+	Assert(topop);
 
 	/* Can't optimize away a recursive UNION */
 	if (root->hasRecursion)
diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c
index 06e843dff0786c3cee96771df4595fb13b528917..1389db18ba2d1a3cce2e8b4a0e52195e12452fdb 100644
--- a/src/backend/optimizer/prep/prepunion.c
+++ b/src/backend/optimizer/prep/prepunion.c
@@ -129,7 +129,7 @@ RelOptInfo *
 plan_set_operations(PlannerInfo *root)
 {
 	Query	   *parse = root->parse;
-	SetOperationStmt *topop = (SetOperationStmt *) parse->setOperations;
+	SetOperationStmt *topop = castNode(SetOperationStmt, parse->setOperations);
 	Node	   *node;
 	RangeTblEntry *leftmostRTE;
 	Query	   *leftmostQuery;
@@ -137,7 +137,7 @@ plan_set_operations(PlannerInfo *root)
 	Path	   *path;
 	List	   *top_tlist;
 
-	Assert(topop && IsA(topop, SetOperationStmt));
+	Assert(topop);
 
 	/* check for unsupported stuff */
 	Assert(parse->jointree->fromlist == NIL);
@@ -1701,12 +1701,11 @@ translate_col_privs(const Bitmapset *parent_privs,
 	attno = InvalidAttrNumber;
 	foreach(lc, translated_vars)
 	{
-		Var		   *var = (Var *) lfirst(lc);
+		Var		   *var = castNode(Var, lfirst(lc));
 
 		attno++;
 		if (var == NULL)		/* ignore dropped columns */
 			continue;
-		Assert(IsA(var, Var));
 		if (whole_row ||
 			bms_is_member(attno - FirstLowInvalidHeapAttributeNumber,
 						  parent_privs))
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 3dedee6d69984b6c906f2ce90de885b43c15f6e2..b19380e1b1ef640e62cde7a4b6f0231296c0a14a 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -2700,9 +2700,8 @@ eval_const_expressions_mutator(Node *node,
 						 * Since the underlying operator is "=", must negate
 						 * its result
 						 */
-						Const	   *csimple = (Const *) simple;
+						Const	   *csimple = castNode(Const, simple);
 
-						Assert(IsA(csimple, Const));
 						csimple->constvalue =
 							BoolGetDatum(!DatumGetBool(csimple->constvalue));
 						return (Node *) csimple;
@@ -3091,12 +3090,10 @@ eval_const_expressions_mutator(Node *node,
 				const_true_cond = false;
 				foreach(arg, caseexpr->args)
 				{
-					CaseWhen   *oldcasewhen = (CaseWhen *) lfirst(arg);
+					CaseWhen   *oldcasewhen = castNode(CaseWhen, lfirst(arg));
 					Node	   *casecond;
 					Node	   *caseresult;
 
-					Assert(IsA(oldcasewhen, CaseWhen));
-
 					/* Simplify this alternative's test condition */
 					casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
 															  context);
@@ -4081,8 +4078,7 @@ fetch_function_defaults(HeapTuple func_tuple)
 	if (isnull)
 		elog(ERROR, "not enough default arguments");
 	str = TextDatumGetCString(proargdefaults);
-	defaults = (List *) stringToNode(str);
-	Assert(IsA(defaults, List));
+	defaults = castNode(List, stringToNode(str));
 	pfree(str);
 	return defaults;
 }
diff --git a/src/backend/optimizer/util/orclauses.c b/src/backend/optimizer/util/orclauses.c
index c965bb678d317d2a459e68a185c60b6ea296f203..9cbcaedb75d02373fc091eaf1fdcd60b96bb4663 100644
--- a/src/backend/optimizer/util/orclauses.c
+++ b/src/backend/optimizer/util/orclauses.c
@@ -188,9 +188,8 @@ extract_or_clause(RestrictInfo *or_rinfo, RelOptInfo *rel)
 
 			foreach(lc2, andargs)
 			{
-				RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc2);
+				RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc2));
 
-				Assert(IsA(rinfo, RestrictInfo));
 				if (restriction_is_or_clause(rinfo))
 				{
 					/*
@@ -211,11 +210,11 @@ extract_or_clause(RestrictInfo *or_rinfo, RelOptInfo *rel)
 		}
 		else
 		{
-			Assert(IsA(orarg, RestrictInfo));
-			Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
-			if (is_safe_restriction_clause_for((RestrictInfo *) orarg, rel))
-				subclauses = lappend(subclauses,
-									 ((RestrictInfo *) orarg)->clause);
+			RestrictInfo *rinfo = castNode(RestrictInfo, orarg);
+
+			Assert(!restriction_is_or_clause(rinfo));
+			if (is_safe_restriction_clause_for(rinfo, rel))
+				subclauses = lappend(subclauses, rinfo->clause);
 		}
 
 		/*
diff --git a/src/backend/optimizer/util/restrictinfo.c b/src/backend/optimizer/util/restrictinfo.c
index 045b5cf53920c7d8c3b7986437e8dc9e9eafef0e..6f79f966544303ddbc649e933f2b4d82c56c6f3e 100644
--- a/src/backend/optimizer/util/restrictinfo.c
+++ b/src/backend/optimizer/util/restrictinfo.c
@@ -335,9 +335,7 @@ get_actual_clauses(List *restrictinfo_list)
 
 	foreach(l, restrictinfo_list)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
-
-		Assert(IsA(rinfo, RestrictInfo));
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
 		Assert(!rinfo->pseudoconstant);
 
@@ -361,9 +359,7 @@ extract_actual_clauses(List *restrictinfo_list,
 
 	foreach(l, restrictinfo_list)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
-
-		Assert(IsA(rinfo, RestrictInfo));
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
 		if (rinfo->pseudoconstant == pseudoconstant)
 			result = lappend(result, rinfo->clause);
@@ -393,9 +389,7 @@ extract_actual_join_clauses(List *restrictinfo_list,
 
 	foreach(l, restrictinfo_list)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
-
-		Assert(IsA(rinfo, RestrictInfo));
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
 
 		if (rinfo->is_pushed_down)
 		{
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 0f7659bb6be5ebfc909ac28682cf68fde6d4070a..796b5c9a5f951172a835c1350ea3e28185c0b0f9 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -824,8 +824,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
 		AttrNumber	attr_num;
 		TargetEntry *tle;
 
-		col = (ResTarget *) lfirst(icols);
-		Assert(IsA(col, ResTarget));
+		col = castNode(ResTarget, lfirst(icols));
 		attr_num = (AttrNumber) lfirst_int(attnos);
 
 		tle = makeTargetEntry(expr,
@@ -950,8 +949,7 @@ transformInsertRow(ParseState *pstate, List *exprlist,
 		Expr	   *expr = (Expr *) lfirst(lc);
 		ResTarget  *col;
 
-		col = (ResTarget *) lfirst(icols);
-		Assert(IsA(col, ResTarget));
+		col = castNode(ResTarget, lfirst(icols));
 
 		expr = transformAssignedExpr(pstate, expr,
 									 EXPR_KIND_INSERT_TARGET,
@@ -1633,10 +1631,9 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
 	/*
 	 * Recursively transform the components of the tree.
 	 */
-	sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
-															true,
-															NULL);
-	Assert(sostmt && IsA(sostmt, SetOperationStmt));
+	sostmt = castNode(SetOperationStmt,
+					  transformSetOperationTree(pstate, stmt, true,	NULL));
+	Assert(sostmt);
 	qry->setOperations = (Node *) sostmt;
 
 	/*
@@ -2298,8 +2295,7 @@ transformUpdateTargetList(ParseState *pstate, List *origTlist)
 		}
 		if (orig_tl == NULL)
 			elog(ERROR, "UPDATE target count mismatch --- internal error");
-		origTarget = (ResTarget *) lfirst(orig_tl);
-		Assert(IsA(origTarget, ResTarget));
+		origTarget = castNode(ResTarget, lfirst(orig_tl));
 
 		attrno = attnameAttNum(pstate->p_target_relation,
 							   origTarget->name, true);
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 07cc81ee7643765f6ffc09f4cc2d104b4b8c9453..6c6d21b5885e7e6787b30ad2adc6f5448726e703 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -3249,8 +3249,7 @@ ColQualList:
 ColConstraint:
 			CONSTRAINT name ColConstraintElem
 				{
-					Constraint *n = (Constraint *) $3;
-					Assert(IsA(n, Constraint));
+					Constraint *n = castNode(Constraint, $3);
 					n->conname = $2;
 					n->location = @1;
 					$$ = (Node *) n;
@@ -3442,8 +3441,7 @@ TableLikeOption:
 TableConstraint:
 			CONSTRAINT name ConstraintElem
 				{
-					Constraint *n = (Constraint *) $3;
-					Assert(IsA(n, Constraint));
+					Constraint *n = castNode(Constraint, $3);
 					n->conname = $2;
 					n->location = @1;
 					$$ = (Node *) n;
@@ -12845,8 +12843,7 @@ c_expr:		columnref								{ $$ = $1; }
 				}
 			| ARRAY array_expr
 				{
-					A_ArrayExpr *n = (A_ArrayExpr *) $2;
-					Assert(IsA(n, A_ArrayExpr));
+					A_ArrayExpr *n = castNode(A_ArrayExpr, $2);
 					/* point outermost A_ArrayExpr to the ARRAY keyword */
 					n->location = @1;
 					$$ = (Node *)n;
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index 69f47364388809e78855e5c093e0a5a92b53e545..fecc1d65984c99ebb5dd46884c421bf813089329 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -903,8 +903,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 		rel = transformFromClauseItem(pstate, rts->relation,
 									  top_rte, top_rti, namespace);
 		/* Currently, grammar could only return a RangeVar as contained rel */
-		Assert(IsA(rel, RangeTblRef));
-		rtr = (RangeTblRef *) rel;
+		rtr = castNode(RangeTblRef, rel);
 		rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
 		/* We only support this on plain relations and matviews */
 		if (rte->relkind != RELKIND_RELATION &&
diff --git a/src/backend/parser/parse_collate.c b/src/backend/parser/parse_collate.c
index 832897f68ddef8039791fb70003c94ddbcad2af4..52ac722790912f3311678dc8a81c3a45591d8405 100644
--- a/src/backend/parser/parse_collate.c
+++ b/src/backend/parser/parse_collate.c
@@ -514,8 +514,7 @@ assign_collations_walker(Node *node, assign_collations_context *context)
 
 				if (qtree->targetList == NIL)
 					return false;
-				tent = (TargetEntry *) linitial(qtree->targetList);
-				Assert(IsA(tent, TargetEntry));
+				tent = castNode(TargetEntry, linitial(qtree->targetList));
 				if (tent->resjunk)
 					return false;
 
@@ -650,9 +649,7 @@ assign_collations_walker(Node *node, assign_collations_context *context)
 
 							foreach(lc, expr->args)
 							{
-								CaseWhen   *when = (CaseWhen *) lfirst(lc);
-
-								Assert(IsA(when, CaseWhen));
+								CaseWhen   *when = castNode(CaseWhen, lfirst(lc));
 
 								/*
 								 * The condition expressions mustn't affect
@@ -868,9 +865,8 @@ assign_aggregate_collations(Aggref *aggref,
 	/* Process aggregated args, holding resjunk ones at arm's length */
 	foreach(lc, aggref->args)
 	{
-		TargetEntry *tle = (TargetEntry *) lfirst(lc);
+		TargetEntry *tle = castNode(TargetEntry, lfirst(lc));
 
-		Assert(IsA(tle, TargetEntry));
 		if (tle->resjunk)
 			assign_expr_collations(loccontext->pstate, (Node *) tle);
 		else
@@ -913,9 +909,8 @@ assign_ordered_set_collations(Aggref *aggref,
 	/* Process aggregated args appropriately */
 	foreach(lc, aggref->args)
 	{
-		TargetEntry *tle = (TargetEntry *) lfirst(lc);
+		TargetEntry *tle = castNode(TargetEntry, lfirst(lc));
 
-		Assert(IsA(tle, TargetEntry));
 		if (merge_sort_collations)
 			(void) assign_collations_walker((Node *) tle, loccontext);
 		else
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 4b732724177e59778f022eb29757cd2b92b728f0..d3ed073cee29e4406c1c24bfc475db4daf9f4aa4 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -917,13 +917,11 @@ transformAExprOp(ParseState *pstate, A_Expr *a)
 		/* ROW() op ROW() is handled specially */
 		lexpr = transformExprRecurse(pstate, lexpr);
 		rexpr = transformExprRecurse(pstate, rexpr);
-		Assert(IsA(lexpr, RowExpr));
-		Assert(IsA(rexpr, RowExpr));
 
 		result = make_row_comparison_op(pstate,
 										a->name,
-										((RowExpr *) lexpr)->args,
-										((RowExpr *) rexpr)->args,
+										castNode(RowExpr, lexpr)->args,
+										castNode(RowExpr, rexpr)->args,
 										a->location);
 	}
 	else
@@ -1296,8 +1294,7 @@ transformAExprBetween(ParseState *pstate, A_Expr *a)
 
 	/* Deconstruct A_Expr into three subexprs */
 	aexpr = a->lexpr;
-	Assert(IsA(a->rexpr, List));
-	args = (List *) a->rexpr;
+	args = castNode(List, a->rexpr);
 	Assert(list_length(args) == 2);
 	bexpr = (Node *) linitial(args);
 	cexpr = (Node *) lsecond(args);
@@ -1672,12 +1669,10 @@ transformCaseExpr(ParseState *pstate, CaseExpr *c)
 	resultexprs = NIL;
 	foreach(l, c->args)
 	{
-		CaseWhen   *w = (CaseWhen *) lfirst(l);
+		CaseWhen   *w = castNode(CaseWhen, lfirst(l));
 		CaseWhen   *neww = makeNode(CaseWhen);
 		Node	   *warg;
 
-		Assert(IsA(w, CaseWhen));
-
 		warg = (Node *) w->expr;
 		if (placeholder)
 		{
@@ -2339,12 +2334,10 @@ transformXmlExpr(ParseState *pstate, XmlExpr *x)
 
 	foreach(lc, x->named_args)
 	{
-		ResTarget  *r = (ResTarget *) lfirst(lc);
+		ResTarget  *r = castNode(ResTarget, lfirst(lc));
 		Node	   *expr;
 		char	   *argname;
 
-		Assert(IsA(r, ResTarget));
-
 		expr = transformExprRecurse(pstate, r->val);
 
 		if (r->name)
@@ -2800,8 +2793,7 @@ make_row_comparison_op(ParseState *pstate, List *opname,
 		Node	   *rarg = (Node *) lfirst(r);
 		OpExpr	   *cmp;
 
-		cmp = (OpExpr *) make_op(pstate, opname, larg, rarg, location);
-		Assert(IsA(cmp, OpExpr));
+		cmp = castNode(OpExpr, make_op(pstate, opname, larg, rarg, location));
 
 		/*
 		 * We don't use coerce_to_boolean here because we insist on the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index a52261f2e92e7058e222bb54c71f7b3e7d6ee8a2..672f7f65f10db7b4d22fc7df89d4b86b820d5067 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -1515,8 +1515,7 @@ func_get_detail(List *funcname,
 											 &isnull);
 			Assert(!isnull);
 			str = TextDatumGetCString(proargdefaults);
-			defaults = (List *) stringToNode(str);
-			Assert(IsA(defaults, List));
+			defaults = castNode(List, stringToNode(str));
 			pfree(str);
 
 			/* Delete any unused defaults from the returned list */
diff --git a/src/backend/parser/parse_node.c b/src/backend/parser/parse_node.c
index 2a5f147ca1d1a294f5c3cd06404c5afe64a94643..30cc7dadca333202a7f28f60ae187993a26fc117 100644
--- a/src/backend/parser/parse_node.c
+++ b/src/backend/parser/parse_node.c
@@ -335,10 +335,9 @@ transformArraySubscripts(ParseState *pstate,
 	 */
 	foreach(idx, indirection)
 	{
-		A_Indices  *ai = (A_Indices *) lfirst(idx);
+		A_Indices  *ai = castNode(A_Indices, lfirst(idx));
 		Node	   *subexpr;
 
-		Assert(IsA(ai, A_Indices));
 		if (isSlice)
 		{
 			if (ai->lidx)
diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c
index e693c316e3b58af2138cd74a6b9078bd6dd045ca..cf69533b53d230ee0277e906a0f17389b17bd2ed 100644
--- a/src/backend/parser/parse_relation.c
+++ b/src/backend/parser/parse_relation.c
@@ -910,12 +910,11 @@ markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
 			JoinExpr   *j;
 
 			if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
-				j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
+				j = castNode(JoinExpr, list_nth(pstate->p_joinexprs, rtindex - 1));
 			else
 				j = NULL;
 			if (j == NULL)
 				elog(ERROR, "could not find JoinExpr for whole-row reference");
-			Assert(IsA(j, JoinExpr));
 
 			/* Note: we can't see FromExpr here */
 			if (IsA(j->larg, RangeTblRef))
diff --git a/src/backend/parser/parse_type.c b/src/backend/parser/parse_type.c
index 8feec0b72b22228ca535c51bacae57e598d9528f..0d7a2b1e1bc84019130b9ae08d14ba343decbd17 100644
--- a/src/backend/parser/parse_type.c
+++ b/src/backend/parser/parse_type.c
@@ -478,9 +478,8 @@ TypeNameListToString(List *typenames)
 	initStringInfo(&string);
 	foreach(l, typenames)
 	{
-		TypeName   *typeName = (TypeName *) lfirst(l);
+		TypeName   *typeName = castNode(TypeName, lfirst(l));
 
-		Assert(IsA(typeName, TypeName));
 		if (l != list_head(typenames))
 			appendStringInfoChar(&string, ',');
 		appendTypeNameToBuffer(typeName, &string);
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index 46e5ae59de73fb7f427713180b0d528c460e4759..ff2bab6551911701e7d9926c306358fe5c83c5a9 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -543,8 +543,7 @@ transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
 
 	foreach(clist, column->constraints)
 	{
-		constraint = lfirst(clist);
-		Assert(IsA(constraint, Constraint));
+		constraint = castNode(Constraint, lfirst(clist));
 
 		switch (constraint->contype)
 		{
@@ -1520,9 +1519,8 @@ transformIndexConstraints(CreateStmtContext *cxt)
 	 */
 	foreach(lc, cxt->ixconstraints)
 	{
-		Constraint *constraint = (Constraint *) lfirst(lc);
+		Constraint *constraint = castNode(Constraint, lfirst(lc));
 
-		Assert(IsA(constraint, Constraint));
 		Assert(constraint->contype == CONSTR_PRIMARY ||
 			   constraint->contype == CONSTR_UNIQUE ||
 			   constraint->contype == CONSTR_EXCLUSION);
@@ -1842,10 +1840,8 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
 			List	   *opname;
 
 			Assert(list_length(pair) == 2);
-			elem = (IndexElem *) linitial(pair);
-			Assert(IsA(elem, IndexElem));
-			opname = (List *) lsecond(pair);
-			Assert(IsA(opname, List));
+			elem = castNode(IndexElem, linitial(pair));
+			opname = castNode(List, lsecond(pair));
 
 			index->indexParams = lappend(index->indexParams, elem);
 			index->excludeOpNames = lappend(index->excludeOpNames, opname);
@@ -1872,8 +1868,7 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
 
 		foreach(columns, cxt->columns)
 		{
-			column = (ColumnDef *) lfirst(columns);
-			Assert(IsA(column, ColumnDef));
+			column = castNode(ColumnDef, lfirst(columns));
 			if (strcmp(column->colname, key) == 0)
 			{
 				found = true;
@@ -1902,11 +1897,10 @@ transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
 
 			foreach(inher, cxt->inhRelations)
 			{
-				RangeVar   *inh = (RangeVar *) lfirst(inher);
+				RangeVar   *inh = castNode(RangeVar, lfirst(inher));
 				Relation	rel;
 				int			count;
 
-				Assert(IsA(inh, RangeVar));
 				rel = heap_openrv(inh, AccessShareLock);
 				/* check user requested inheritance from valid relkind */
 				if (rel->rd_rel->relkind != RELKIND_RELATION &&
@@ -2586,9 +2580,8 @@ transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
 			case AT_AddColumn:
 			case AT_AddColumnToView:
 				{
-					ColumnDef  *def = (ColumnDef *) cmd->def;
+					ColumnDef  *def = castNode(ColumnDef, cmd->def);
 
-					Assert(IsA(def, ColumnDef));
 					transformColumnDefinition(&cxt, def);
 
 					/*
@@ -2693,9 +2686,8 @@ transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
 	 */
 	foreach(l, cxt.alist)
 	{
-		IndexStmt  *idxstmt = (IndexStmt *) lfirst(l);
+		IndexStmt  *idxstmt = castNode(IndexStmt, lfirst(l));
 
-		Assert(IsA(idxstmt, IndexStmt));
 		idxstmt = transformIndexStmt(relid, idxstmt, queryString);
 		newcmd = makeNode(AlterTableCmd);
 		newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c
index d3e44fb135056281e04eb4c1ab4e76a02decbd06..20bbb3748459bb2442569d4a89c7eca500651666 100644
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -2320,8 +2320,7 @@ view_cols_are_auto_updatable(Query *viewquery,
 	 * there should be a single base relation.
 	 */
 	Assert(list_length(viewquery->jointree->fromlist) == 1);
-	rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
-	Assert(IsA(rtr, RangeTblRef));
+	rtr = castNode(RangeTblRef, linitial(viewquery->jointree->fromlist));
 
 	/* Initialize the optional return values */
 	if (updatable_cols != NULL)
@@ -2578,8 +2577,7 @@ adjust_view_column_set(Bitmapset *cols, List *targetlist)
 
 				if (tle->resjunk)
 					continue;
-				var = (Var *) tle->expr;
-				Assert(IsA(var, Var));
+				var = castNode(Var, tle->expr);
 				result = bms_add_member(result,
 						 var->varattno - FirstLowInvalidHeapAttributeNumber);
 			}
@@ -2761,8 +2759,7 @@ rewriteTargetView(Query *parsetree, Relation view)
 	 * view contains a single base relation.
 	 */
 	Assert(list_length(viewquery->jointree->fromlist) == 1);
-	rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
-	Assert(IsA(rtr, RangeTblRef));
+	rtr = castNode(RangeTblRef, linitial(viewquery->jointree->fromlist));
 
 	base_rt_index = rtr->rtindex;
 	base_rte = rt_fetch(base_rt_index, viewquery->rtable);
@@ -3119,11 +3116,9 @@ RewriteQuery(Query *parsetree, List *rewrite_events)
 	foreach(lc1, parsetree->cteList)
 	{
 		CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc1);
-		Query	   *ctequery = (Query *) cte->ctequery;
+		Query	   *ctequery = castNode(Query, cte->ctequery);
 		List	   *newstuff;
 
-		Assert(IsA(ctequery, Query));
-
 		if (ctequery->commandType == CMD_SELECT)
 			continue;
 
@@ -3137,8 +3132,7 @@ RewriteQuery(Query *parsetree, List *rewrite_events)
 		if (list_length(newstuff) == 1)
 		{
 			/* Push the single Query back into the CTE node */
-			ctequery = (Query *) linitial(newstuff);
-			Assert(IsA(ctequery, Query));
+			ctequery = castNode(Query, linitial(newstuff));
 			/* WITH queries should never be canSetTag */
 			Assert(!ctequery->canSetTag);
 			cte->ctequery = (Node *) ctequery;
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 7ada0e58339637d197e6c315ff5580fdf2b68158..8424372bfe1f14aa77209b2f18ddce22fe5b82e0 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -4591,11 +4591,10 @@ CheckDateTokenTables(void)
 Node *
 TemporalTransform(int32 max_precis, Node *node)
 {
-	FuncExpr   *expr = (FuncExpr *) node;
+	FuncExpr   *expr = castNode(FuncExpr, node);
 	Node	   *ret = NULL;
 	Node	   *typmod;
 
-	Assert(IsA(expr, FuncExpr));
 	Assert(list_length(expr->args) >= 2);
 
 	typmod = (Node *) lsecond(expr->args);
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index fa4e1b1e628aef0c3d6c1a212e1f73484630cddf..781c713f81ea4dda608859c91d0053270276d7e9 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -889,11 +889,10 @@ numeric_send(PG_FUNCTION_ARGS)
 Datum
 numeric_transform(PG_FUNCTION_ARGS)
 {
-	FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
+	FuncExpr   *expr = castNode(FuncExpr, PG_GETARG_POINTER(0));
 	Node	   *ret = NULL;
 	Node	   *typmod;
 
-	Assert(IsA(expr, FuncExpr));
 	Assert(list_length(expr->args) >= 2);
 
 	typmod = (Node *) lsecond(expr->args);
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index f355954b536dfe1334091a29bfe666f8003d2368..b27b77de216e26676ce2b7de0e9110c399e3ad59 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -2569,8 +2569,7 @@ print_function_arguments(StringInfo buf, HeapTuple proctup,
 			List	   *argdefaults;
 
 			str = TextDatumGetCString(proargdefaults);
-			argdefaults = (List *) stringToNode(str);
-			Assert(IsA(argdefaults, List));
+			argdefaults = castNode(List, stringToNode(str));
 			pfree(str);
 			nextargdefault = list_head(argdefaults);
 			/* nlackdefaults counts only *input* arguments lacking defaults */
@@ -2762,8 +2761,7 @@ pg_get_function_arg_default(PG_FUNCTION_ARGS)
 	}
 
 	str = TextDatumGetCString(proargdefaults);
-	argdefaults = (List *) stringToNode(str);
-	Assert(IsA(argdefaults, List));
+	argdefaults = castNode(List, stringToNode(str));
 	pfree(str);
 
 	proc = (Form_pg_proc) GETSTRUCT(proctup);
@@ -7654,9 +7652,8 @@ get_rule_expr(Node *node, deparse_context *context,
 				appendStringInfoString(buf, "(alternatives: ");
 				foreach(lc, asplan->subplans)
 				{
-					SubPlan    *splan = (SubPlan *) lfirst(lc);
+					SubPlan    *splan = castNode(SubPlan, lfirst(lc));
 
-					Assert(IsA(splan, SubPlan));
 					if (splan->useHashTable)
 						appendStringInfo(buf, "hashed %s", splan->plan_name);
 					else
@@ -8210,8 +8207,7 @@ get_rule_expr(Node *node, deparse_context *context,
 							get_rule_expr((Node *) linitial(xexpr->args),
 										  context, true);
 
-							con = (Const *) lsecond(xexpr->args);
-							Assert(IsA(con, Const));
+							con = castNode(Const, lsecond(xexpr->args));
 							Assert(!con->constisnull);
 							if (DatumGetBool(con->constvalue))
 								appendStringInfoString(buf,
@@ -8234,8 +8230,7 @@ get_rule_expr(Node *node, deparse_context *context,
 							else
 								get_rule_expr((Node *) con, context, false);
 
-							con = (Const *) lthird(xexpr->args);
-							Assert(IsA(con, Const));
+							con = castNode(Const, lthird(xexpr->args));
 							if (con->constisnull)
 								 /* suppress STANDALONE NO VALUE */ ;
 							else
@@ -8743,10 +8738,9 @@ get_agg_expr(Aggref *aggref, deparse_context *context,
 	 */
 	if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
 	{
-		TargetEntry *tle = linitial(aggref->args);
+		TargetEntry *tle = castNode(TargetEntry, linitial(aggref->args));
 
 		Assert(list_length(aggref->args) == 1);
-		Assert(IsA(tle, TargetEntry));
 		resolve_special_varno((Node *) tle->expr, context, original_aggref,
 							  get_agg_combine_expr);
 		return;
@@ -9205,9 +9199,8 @@ get_sublink_expr(SubLink *sublink, deparse_context *context)
 			sep = "";
 			foreach(l, ((BoolExpr *) sublink->testexpr)->args)
 			{
-				OpExpr	   *opexpr = (OpExpr *) lfirst(l);
+				OpExpr	   *opexpr = castNode(OpExpr, lfirst(l));
 
-				Assert(IsA(opexpr, OpExpr));
 				appendStringInfoString(buf, sep);
 				get_rule_expr(linitial(opexpr->args), context, true);
 				if (!opname)
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index d14f0f97a8a523acf5c3f578e1b4d67f6a5de875..13cb1facd49907308f722e3088f58b813f3f7d8a 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -6087,14 +6087,13 @@ deconstruct_indexquals(IndexPath *path)
 
 	forboth(lcc, path->indexquals, lci, path->indexqualcols)
 	{
-		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
+		RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lcc));
 		int			indexcol = lfirst_int(lci);
 		Expr	   *clause;
 		Node	   *leftop,
 				   *rightop;
 		IndexQualInfo *qinfo;
 
-		Assert(IsA(rinfo, RestrictInfo));
 		clause = rinfo->clause;
 
 		qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 9b4c012a63c4dc937c1c4c260560744a6ba69810..997a551bd87a47102c5537d1b81fc0f1b229dd31 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -1309,11 +1309,10 @@ intervaltypmodleastfield(int32 typmod)
 Datum
 interval_transform(PG_FUNCTION_ARGS)
 {
-	FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
+	FuncExpr   *expr = castNode(FuncExpr, PG_GETARG_POINTER(0));
 	Node	   *ret = NULL;
 	Node	   *typmod;
 
-	Assert(IsA(expr, FuncExpr));
 	Assert(list_length(expr->args) >= 2);
 
 	typmod = (Node *) lsecond(expr->args);
diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c
index af39d4cf25aeac41ae906c598a3b2d250b4839a0..e947785d8189934cc8b287676320b264ad5c4370 100644
--- a/src/backend/utils/adt/varbit.c
+++ b/src/backend/utils/adt/varbit.c
@@ -679,11 +679,10 @@ varbit_send(PG_FUNCTION_ARGS)
 Datum
 varbit_transform(PG_FUNCTION_ARGS)
 {
-	FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
+	FuncExpr   *expr = castNode(FuncExpr, PG_GETARG_POINTER(0));
 	Node	   *ret = NULL;
 	Node	   *typmod;
 
-	Assert(IsA(expr, FuncExpr));
 	Assert(list_length(expr->args) >= 2);
 
 	typmod = (Node *) lsecond(expr->args);
diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c
index c800beb08f8904c22f4cd0aa6613c13c55ca52a4..6f2f9f66339ec2f1ff48c011bdf5a48cf2a0847c 100644
--- a/src/backend/utils/adt/varchar.c
+++ b/src/backend/utils/adt/varchar.c
@@ -554,11 +554,10 @@ varcharsend(PG_FUNCTION_ARGS)
 Datum
 varchar_transform(PG_FUNCTION_ARGS)
 {
-	FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
+	FuncExpr   *expr = castNode(FuncExpr, PG_GETARG_POINTER(0));
 	Node	   *ret = NULL;
 	Node	   *typmod;
 
-	Assert(IsA(expr, FuncExpr));
 	Assert(list_length(expr->args) >= 2);
 
 	typmod = (Node *) lsecond(expr->args);
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 5d8fb2edb8f506dbedc3ec9aa7a1fa8051df91a0..24771389c84013d53b8d34d62008ba736d11faf1 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -7322,7 +7322,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 			}
 			else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
 			{
-				A_Const    *con = (A_Const *) linitial(stmt->args);
+				A_Const    *con = castNode(A_Const, linitial(stmt->args));
 
 				if (stmt->is_local)
 					ereport(ERROR,
@@ -7330,7 +7330,6 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 							 errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
 
 				WarnNoTransactionChain(isTopLevel, "SET TRANSACTION");
-				Assert(IsA(con, A_Const));
 				Assert(nodeTag(&con->val) == T_String);
 				ImportSnapshot(strVal(&con->val));
 			}
diff --git a/src/pl/plpgsql/src/pl_handler.c b/src/pl/plpgsql/src/pl_handler.c
index e15be5d9ac2f854a85879d54fc1c8aa6a2744fb1..92d15810d7f6cc283d6cb8ceac090afa19161110 100644
--- a/src/pl/plpgsql/src/pl_handler.c
+++ b/src/pl/plpgsql/src/pl_handler.c
@@ -288,7 +288,7 @@ PG_FUNCTION_INFO_V1(plpgsql_inline_handler);
 Datum
 plpgsql_inline_handler(PG_FUNCTION_ARGS)
 {
-	InlineCodeBlock *codeblock = (InlineCodeBlock *) DatumGetPointer(PG_GETARG_DATUM(0));
+	InlineCodeBlock *codeblock = castNode(InlineCodeBlock, DatumGetPointer(PG_GETARG_DATUM(0)));
 	PLpgSQL_function *func;
 	FunctionCallInfoData fake_fcinfo;
 	FmgrInfo	flinfo;
@@ -296,8 +296,6 @@ plpgsql_inline_handler(PG_FUNCTION_ARGS)
 	Datum		retval;
 	int			rc;
 
-	Assert(IsA(codeblock, InlineCodeBlock));
-
 	/*
 	 * Connect to SPI manager
 	 */
diff --git a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
index 2fe6903ba305b57d2a312dc0604ce367207f7b89..56394de92e7bf14d4585cd0436509653d3888395 100644
--- a/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
+++ b/src/test/modules/test_ddl_deparse/test_ddl_deparse.c
@@ -94,11 +94,9 @@ get_altertable_subcmdtypes(PG_FUNCTION_ARGS)
 	foreach(cell, cmd->d.alterTable.subcmds)
 	{
 		CollectedATSubcmd *sub = lfirst(cell);
-		AlterTableCmd *subcmd = (AlterTableCmd *) sub->parsetree;
+		AlterTableCmd *subcmd = castNode(AlterTableCmd, sub->parsetree);
 		const char *strtype;
 
-		Assert(IsA(subcmd, AlterTableCmd));
-
 		switch (subcmd->subtype)
 		{
 			case AT_AddColumn: