diff --git a/src/backend/tsearch/to_tsany.c b/src/backend/tsearch/to_tsany.c
index b92a5aa6e5dfbe19ed057492a047bc6468a61943..da9ae8d5ba8fa2ad717396d17cde3c6e3b7b9aa7 100644
--- a/src/backend/tsearch/to_tsany.c
+++ b/src/backend/tsearch/to_tsany.c
@@ -340,6 +340,7 @@ to_tsquery_byid(PG_FUNCTION_ARGS)
 	if (query->size == 0)
 		PG_RETURN_TSQUERY(query);
 
+	/* clean out any stopword placeholders from the tree */
 	res = clean_fakeval(GETQUERY(query), &len);
 	if (!res)
 	{
@@ -349,6 +350,10 @@ to_tsquery_byid(PG_FUNCTION_ARGS)
 	}
 	memcpy((void *) GETQUERY(query), (void *) res, len * sizeof(QueryItem));
 
+	/*
+	 * Removing the stopword placeholders might've resulted in fewer
+	 * QueryItems. If so, move the operands up accordingly.
+	 */
 	if (len != query->size)
 	{
 		char	   *oldoperand = GETOPERAND(query);
@@ -357,7 +362,7 @@ to_tsquery_byid(PG_FUNCTION_ARGS)
 		Assert(len < query->size);
 
 		query->size = len;
-		memcpy((void *) GETOPERAND(query), oldoperand, VARSIZE(query) - (oldoperand - (char *) query));
+		memmove((void *) GETOPERAND(query), oldoperand, VARSIZE(query) - (oldoperand - (char *) query));
 		SET_VARSIZE(query, COMPUTESIZE(len, lenoperand));
 	}