[PATCH] Redudant initilization

Started by Ranier Vilelaalmost 6 years ago13 messages
#1Ranier Vilela
ranier.vf@gmail.com
1 attachment(s)

Hi,
This patch fixes some redundant initilization, that are safe to remove.

best regards,
Ranier Vilela

Attachments:

redudant_initialization.patchapplication/octet-stream; name=redudant_initialization.patchDownload
diff --git a/src/backend/access/gist/gistxlog.c b/src/backend/access/gist/gistxlog.c
index d3f3a7b803..ffaa2b1ab4 100644
--- a/src/backend/access/gist/gistxlog.c
+++ b/src/backend/access/gist/gistxlog.c
@@ -396,7 +396,7 @@ gistRedoPageReuse(XLogReaderState *record)
 	if (InHotStandby)
 	{
 		FullTransactionId latestRemovedFullXid = xlrec->latestRemovedFullXid;
-		FullTransactionId nextFullXid = ReadNextFullTransactionId();
+		FullTransactionId nextFullXid;
 		uint64		diff;
 
 		/*
 
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 9d9e915979..795cf349eb 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -3396,7 +3396,7 @@ List *
 heap_truncate_find_FKs(List *relationIds)
 {
 	List	   *result = NIL;
-	List	   *oids = list_copy(relationIds);
+	List	   *oids;
 	List	   *parent_cons;
 	ListCell   *cell;
 	ScanKeyData key;
 
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index c5b771c531..37fbeef841 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -730,9 +730,11 @@ mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
 BlockNumber
 mdnblocks(SMgrRelation reln, ForkNumber forknum)
 {
-	MdfdVec    *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
+	MdfdVec    *v;
 	BlockNumber nblocks;
-	BlockNumber segno = 0;
+	BlockNumber segno;
+
+    mdopenfork(reln, forknum, EXTENSION_FAIL);
 
 	/* mdopen has opened the first segment */
 	Assert(reln->md_num_open_segs[forknum] > 0);
 
diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 8bb00abb6b..7a6a2ecbe9 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -990,7 +990,7 @@ catenate_stringinfo_string(StringInfo buffer, const char *addon)
 Datum
 json_build_object(PG_FUNCTION_ARGS)
 {
-	int			nargs = PG_NARGS();
+	int			nargs;
 	int			i;
 	const char *sep = "";
 	StringInfo	result;
@@ -998,6 +998,8 @@ json_build_object(PG_FUNCTION_ARGS)
 	bool	   *nulls;
 	Oid		   *types;
 
+    PG_NARGS();
+
 	/* fetch argument values to build the object */
 	nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);
 
diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 9e24fec72d..fb0e833b2d 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -475,7 +475,7 @@ MemoryContextMemAllocated(MemoryContext context, bool recurse)
 
 	if (recurse)
 	{
-		MemoryContext child = context->firstchild;
+		MemoryContext child;
 
 		for (child = context->firstchild;
 			 child != NULL;
#2Kyotaro Horiguchi
horikyota.ntt@gmail.com
In reply to: Ranier Vilela (#1)
Re: [PATCH] Redudant initilization

Hello.

At Sat, 28 Mar 2020 19:04:00 -0300, Ranier Vilela <ranier.vf@gmail.com> wrote in

Hi,
This patch fixes some redundant initilization, that are safe to remove.

diff --git a/src/backend/access/gist/gistxlog.c b/src/backend/access/gist/gistxlog.c
index d3f3a7b803..ffaa2b1ab4 100644
--- a/src/backend/access/gist/gistxlog.c
+++ b/src/backend/access/gist/gistxlog.c
@@ -396,7 +396,7 @@ gistRedoPageReuse(XLogReaderState *record)
if (InHotStandby)
{
FullTransactionId latestRemovedFullXid = xlrec->latestRemovedFullXid;
-		FullTransactionId nextFullXid = ReadNextFullTransactionId();
+		FullTransactionId nextFullXid;

I'd prefer to preserve this and remove the latter.

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 9d9e915979..795cf349eb 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -3396,7 +3396,7 @@ List *
heap_truncate_find_FKs(List *relationIds)
{
List	   *result = NIL;
-	List	   *oids = list_copy(relationIds);
+	List	   *oids;

This was just a waste of memory, the fix looks fine.

diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index c5b771c531..37fbeef841 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -730,9 +730,11 @@ mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
BlockNumber
mdnblocks(SMgrRelation reln, ForkNumber forknum)
{
-	MdfdVec    *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
+	MdfdVec    *v;
BlockNumber nblocks;
-	BlockNumber segno = 0;
+	BlockNumber segno;
+
+    mdopenfork(reln, forknum, EXTENSION_FAIL);

/* mdopen has opened the first segment */
Assert(reln->md_num_open_segs[forknum] > 0);

It doesn't seems *to me* an issue.

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 8bb00abb6b..7a6a2ecbe9 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -990,7 +990,7 @@ catenate_stringinfo_string(StringInfo buffer, const char *addon)
Datum
json_build_object(PG_FUNCTION_ARGS)
{
-	int			nargs = PG_NARGS();
+	int			nargs;

This part looks fine.

int i;
const char *sep = "";
StringInfo result;
@@ -998,6 +998,8 @@ json_build_object(PG_FUNCTION_ARGS)
bool *nulls;
Oid *types;

+    PG_NARGS();
+
/* fetch argument values to build the object */
nargs = extract_variadic_args(fcinfo, 0, false, &args, &types, &nulls);

PG_NARGS() doesn't have a side-effect so no need to call independently.

diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 9e24fec72d..fb0e833b2d 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -475,7 +475,7 @@ MemoryContextMemAllocated(MemoryContext context, bool recurse)
if (recurse)
{
-		MemoryContext child = context->firstchild;
+		MemoryContext child;

for (child = context->firstchild;
child != NULL;

This looks fine.

regards.

--
Kyotaro Horiguchi
NTT Open Source Software Center

#3Ranier Vilela
ranier.vf@gmail.com
In reply to: Kyotaro Horiguchi (#2)
Re: [PATCH] Redudant initilization

Em dom., 29 de mar. de 2020 às 21:57, Kyotaro Horiguchi <
horikyota.ntt@gmail.com> escreveu:

Hello.

At Sat, 28 Mar 2020 19:04:00 -0300, Ranier Vilela <ranier.vf@gmail.com>
wrote in

Hi,
This patch fixes some redundant initilization, that are safe to remove.

diff --git a/src/backend/access/gist/gistxlog.c

b/src/backend/access/gist/gistxlog.c

index d3f3a7b803..ffaa2b1ab4 100644
--- a/src/backend/access/gist/gistxlog.c
+++ b/src/backend/access/gist/gistxlog.c
@@ -396,7 +396,7 @@ gistRedoPageReuse(XLogReaderState *record)
if (InHotStandby)
{
FullTransactionId latestRemovedFullXid =

xlrec->latestRemovedFullXid;

- FullTransactionId nextFullXid =

ReadNextFullTransactionId();

+ FullTransactionId nextFullXid;

I'd prefer to preserve this and remove the latter.

Ok.

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 9d9e915979..795cf349eb 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -3396,7 +3396,7 @@ List *
heap_truncate_find_FKs(List *relationIds)
{
List       *result = NIL;
-     List       *oids = list_copy(relationIds);
+     List       *oids;

This was just a waste of memory, the fix looks fine.

diff --git a/src/backend/storage/smgr/md.c

b/src/backend/storage/smgr/md.c

index c5b771c531..37fbeef841 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -730,9 +730,11 @@ mdwrite(SMgrRelation reln, ForkNumber forknum,

BlockNumber blocknum,

BlockNumber
mdnblocks(SMgrRelation reln, ForkNumber forknum)
{
-     MdfdVec    *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
+     MdfdVec    *v;
BlockNumber nblocks;
-     BlockNumber segno = 0;
+     BlockNumber segno;
+
+    mdopenfork(reln, forknum, EXTENSION_FAIL);

/* mdopen has opened the first segment */
Assert(reln->md_num_open_segs[forknum] > 0);

It doesn't seems *to me* an issue.

Not a big deal, but the assignment of the variable v here is a small waste,
since it is again highlighted right after.

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 8bb00abb6b..7a6a2ecbe9 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -990,7 +990,7 @@ catenate_stringinfo_string(StringInfo buffer, const

char *addon)

Datum
json_build_object(PG_FUNCTION_ARGS)
{
-     int                     nargs = PG_NARGS();
+     int                     nargs;

This part looks fine.

int i;
const char *sep = "";
StringInfo result;
@@ -998,6 +998,8 @@ json_build_object(PG_FUNCTION_ARGS)
bool *nulls;
Oid *types;

+    PG_NARGS();
+
/* fetch argument values to build the object */
nargs = extract_variadic_args(fcinfo, 0, false, &args, &types,

&nulls);

PG_NARGS() doesn't have a side-effect so no need to call independently.

Sorry, does that mean we can remove it completely?

diff --git a/src/backend/utils/mmgr/mcxt.c

b/src/backend/utils/mmgr/mcxt.c

index 9e24fec72d..fb0e833b2d 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -475,7 +475,7 @@ MemoryContextMemAllocated(MemoryContext context,

bool recurse)

if (recurse)
{
-             MemoryContext child = context->firstchild;
+             MemoryContext child;

for (child = context->firstchild;
child != NULL;

This looks fine.

Thank you for the review and consideration.

best regards,
Ranier Vilela

#4Ranier Vilela
ranier.vf@gmail.com
In reply to: Ranier Vilela (#3)
1 attachment(s)
Re: [PATCH] Redudant initilization

Hi,
New patch with yours suggestions.

best regards,
Ranier Vilela

Attachments:

v2_redundant_initialization.patchapplication/octet-stream; name=v2_redundant_initialization.patchDownload
diff --git a/src/backend/access/gist/gistxlog.c b/src/backend/access/gist/gistxlog.c
index d3f3a7b803..ed7c99226b 100644
--- a/src/backend/access/gist/gistxlog.c
+++ b/src/backend/access/gist/gistxlog.c
@@ -405,7 +405,6 @@ gistRedoPageReuse(XLogReaderState *record)
 		 * logged value is very old, so that XID wrap-around already happened
 		 * on it, there can't be any snapshots that still see it.
 		 */
-		nextFullXid = ReadNextFullTransactionId();
 		diff = U64FromFullTransactionId(nextFullXid) -
 			U64FromFullTransactionId(latestRemovedFullXid);
 		if (diff < MaxTransactionId / 2)

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 9d9e915979..795cf349eb 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -3396,7 +3396,7 @@ List *
 heap_truncate_find_FKs(List *relationIds)
 {
 	List	   *result = NIL;
-	List	   *oids = list_copy(relationIds);
+	List	   *oids;
 	List	   *parent_cons;
 	ListCell   *cell;
 	ScanKeyData key;

diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index c5b771c531..37fbeef841 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -730,9 +730,11 @@ mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
 BlockNumber
 mdnblocks(SMgrRelation reln, ForkNumber forknum)
 {
-	MdfdVec    *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
+	MdfdVec    *v;
 	BlockNumber nblocks;
-	BlockNumber segno = 0;
+	BlockNumber segno;
+
+    mdopenfork(reln, forknum, EXTENSION_FAIL);
 
 	/* mdopen has opened the first segment */
 	Assert(reln->md_num_open_segs[forknum] > 0);

diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 8bb00abb6b..d75b8e79da 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -990,7 +990,7 @@ catenate_stringinfo_string(StringInfo buffer, const char *addon)
 Datum
 json_build_object(PG_FUNCTION_ARGS)
 {
-	int			nargs = PG_NARGS();
+	int			nargs;
 	int			i;
 	const char *sep = "";
 	StringInfo	result;

diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 9e24fec72d..fb0e833b2d 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -475,7 +475,7 @@ MemoryContextMemAllocated(MemoryContext context, bool recurse)
 
 	if (recurse)
 	{
-		MemoryContext child = context->firstchild;
+		MemoryContext child;
 
 		for (child = context->firstchild;
 			 child != NULL;
#5Bruce Momjian
bruce@momjian.us
In reply to: Ranier Vilela (#4)
Re: [PATCH] Redudant initilization

On Wed, Apr 1, 2020 at 08:57:18AM -0300, Ranier Vilela wrote:

Hi,
New patch with yours suggestions.

Patch applied to head, thanks.

--
Bruce Momjian <bruce@momjian.us> https://momjian.us
EnterpriseDB https://enterprisedb.com

The usefulness of a cup is in its emptiness, Bruce Lee

#6Ranier Vilela
ranier.vf@gmail.com
In reply to: Bruce Momjian (#5)
Re: [PATCH] Redudant initilization

Em qui., 3 de set. de 2020 às 23:57, Bruce Momjian <bruce@momjian.us>
escreveu:

On Wed, Apr 1, 2020 at 08:57:18AM -0300, Ranier Vilela wrote:

Hi,
New patch with yours suggestions.

Patch applied to head, thanks.

Thank you Bruce.

regards,
Ranier Vilela

#7Bruce Momjian
bruce@momjian.us
In reply to: Ranier Vilela (#6)
Re: [PATCH] Redudant initilization

On Fri, Sep 4, 2020 at 09:39:45AM -0300, Ranier Vilela wrote:

Em qui., 3 de set. de 2020 �s 23:57, Bruce Momjian <bruce@momjian.us> escreveu:

On Wed, Apr� 1, 2020 at 08:57:18AM -0300, Ranier Vilela wrote:

Hi,
New patch with yours suggestions.

Patch applied to head, thanks.

Thank you Bruce.

I have to say, I am kind of stumped why compilers do not warn of such
cases, and why we haven't gotten reports about these cases before.

--
Bruce Momjian <bruce@momjian.us> https://momjian.us
EnterpriseDB https://enterprisedb.com

The usefulness of a cup is in its emptiness, Bruce Lee

#8Ranier Vilela
ranier.vf@gmail.com
In reply to: Bruce Momjian (#7)
Re: [PATCH] Redudant initilization

Em sex., 4 de set. de 2020 às 11:01, Bruce Momjian <bruce@momjian.us>
escreveu:

On Fri, Sep 4, 2020 at 09:39:45AM -0300, Ranier Vilela wrote:

Em qui., 3 de set. de 2020 às 23:57, Bruce Momjian <bruce@momjian.us>

escreveu:

On Wed, Apr 1, 2020 at 08:57:18AM -0300, Ranier Vilela wrote:

Hi,
New patch with yours suggestions.

Patch applied to head, thanks.

Thank you Bruce.

I have to say, I am kind of stumped why compilers do not warn of such
cases, and why we haven't gotten reports about these cases before.

I believe it is because, syntactically, there is no error.

I would like to thank Kyotaro Horiguchi,
my thanks for your review.

regards,
Ranier Vilela

#9Tom Lane
tgl@sss.pgh.pa.us
In reply to: Bruce Momjian (#7)
Re: [PATCH] Redudant initilization

Bruce Momjian <bruce@momjian.us> writes:

I have to say, I am kind of stumped why compilers do not warn of such
cases, and why we haven't gotten reports about these cases before.

I was just experimenting with clang's "scan-build" tool. It finds
all of the cases you just fixed, and several dozen more beside.
Quite a few are things that, as a matter of style, we should *not*
change, for instance

rewriteHandler.c:2807:5: warning: Value stored to 'outer_reloids' is never read
outer_reloids = list_delete_last(outer_reloids);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Failing to update the list pointer here would just be asking for bugs.
However, I see some that look like genuine oversights; will go fix.

(I'm not sure how much I trust scan-build overall. It produces a
whole bunch of complaints about null pointer dereferences, for instance.
If those aren't 99% false positives, we'd be crashing constantly.
It's also dog-slow. But it might be something to try occasionally.)

regards, tom lane

#10Ranier Vilela
ranier.vf@gmail.com
In reply to: Tom Lane (#9)
1 attachment(s)
Re: [PATCH] Redudant initilization

Em sex., 4 de set. de 2020 às 14:40, Tom Lane <tgl@sss.pgh.pa.us> escreveu:

Bruce Momjian <bruce@momjian.us> writes:

I have to say, I am kind of stumped why compilers do not warn of such
cases, and why we haven't gotten reports about these cases before.

I was just experimenting with clang's "scan-build" tool. It finds
all of the cases you just fixed, and several dozen more beside.
Quite a few are things that, as a matter of style, we should *not*
change, for instance

rewriteHandler.c:2807:5: warning: Value stored to 'outer_reloids' is never
read
outer_reloids =
list_delete_last(outer_reloids);
^
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are some like this, in the analyzes that I did.
Even when it is the last action of the function.

Failing to update the list pointer here would just be asking for bugs.
However, I see some that look like genuine oversights; will go fix.

Thanks for fixing this.

(I'm not sure how much I trust scan-build overall. It produces a
whole bunch of complaints about null pointer dereferences, for instance.
If those aren't 99% false positives, we'd be crashing constantly.
It's also dog-slow. But it might be something to try occasionally.)

I believe it would be very beneficial.

Attached is a patch I made in March/2020, but due to problems,
it was sent but did not make the list.
Would you mind taking a look?
Certainly, if accepted, rebasing would have to be done.

regards,
Ranier Vilela

Attachments:

variables_assigned_unused_value.patchapplication/octet-stream; name=variables_assigned_unused_value.patchDownload
diff --git a/src/backend/access/common/heaptuple.c b/src/backend/access/common/heaptuple.c
index f89769f379..04b27f1e6e 100644
--- a/src/backend/access/common/heaptuple.c
+++ b/src/backend/access/common/heaptuple.c
@@ -736,7 +736,6 @@ expand_tuple(HeapTuple *targetHeapTuple,
 {
 	AttrMissing *attrmiss = NULL;
 	int			attnum;
-	int			firstmissingnum = 0;
 	bool		hasNulls = HeapTupleHasNulls(sourceTuple);
 	HeapTupleHeader targetTHeader;
 	HeapTupleHeader sourceTHeader = sourceTuple->t_data;
@@ -765,6 +764,8 @@ expand_tuple(HeapTuple *targetHeapTuple,
 	if (tupleDesc->constr &&
 		tupleDesc->constr->missing)
 	{
+	    int			firstmissingnum;
+
 		/*
 		 * If there are missing values we want to put them into the tuple.
 		 * Before that we have to compute the extra length for the values
diff --git a/src/backend/access/gin/ginbtree.c b/src/backend/access/gin/ginbtree.c
index 8d08b05f51..82788a5c36 100644
--- a/src/backend/access/gin/ginbtree.c
+++ b/src/backend/access/gin/ginbtree.c
@@ -241,7 +241,6 @@ ginFindParents(GinBtree btree, GinBtreeStack *stack)
 
 	blkno = root->blkno;
 	buffer = root->buffer;
-	offset = InvalidOffsetNumber;
 
 	ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
 
diff --git a/src/backend/access/gist/gistutil.c b/src/backend/access/gist/gistutil.c
index dd975b164c..cc126236a1 100644
--- a/src/backend/access/gist/gistutil.c
+++ b/src/backend/access/gist/gistutil.c
@@ -32,7 +32,7 @@
 void
 gistfillbuffer(Page page, IndexTuple *itup, int len, OffsetNumber off)
 {
-	OffsetNumber l = InvalidOffsetNumber;
+	OffsetNumber l;
 	int			i;
 
 	if (off == InvalidOffsetNumber)
diff --git a/src/backend/access/hash/hashsearch.c b/src/backend/access/hash/hashsearch.c
index 995498e48d..d56ffe3b3e 100644
--- a/src/backend/access/hash/hashsearch.c
+++ b/src/backend/access/hash/hashsearch.c
@@ -470,7 +470,7 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 
 	if (ScanDirectionIsForward(dir))
 	{
-		BlockNumber prev_blkno = InvalidBlockNumber;
+		BlockNumber prev_blkno;
 
 		for (;;)
 		{
diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c
index 8ff49ce6d6..32e80337b0 100644
--- a/src/backend/access/nbtree/nbtsearch.c
+++ b/src/backend/access/nbtree/nbtsearch.c
@@ -1863,7 +1863,7 @@ _bt_steppage(IndexScanDesc scan, ScanDirection dir)
 {
 	BTScanOpaque so = (BTScanOpaque) scan->opaque;
 	BlockNumber blkno = InvalidBlockNumber;
-	bool		status = true;
+	bool		status;
 
 	Assert(BTScanPosIsValid(so->currPos));
 
@@ -1972,7 +1972,7 @@ _bt_readnextpage(IndexScanDesc scan, BlockNumber blkno, ScanDirection dir)
 	Relation	rel;
 	Page		page;
 	BTPageOpaque opaque;
-	bool		status = true;
+	bool		status;
 
 	rel = scan->indexRelation;
 
diff --git a/src/backend/access/nbtree/nbtsplitloc.c b/src/backend/access/nbtree/nbtsplitloc.c
index 8ba055be9e..15ac106525 100644
--- a/src/backend/access/nbtree/nbtsplitloc.c
+++ b/src/backend/access/nbtree/nbtsplitloc.c
@@ -812,7 +812,6 @@ _bt_bestsplitloc(FindSplitData *state, int perfectpenalty,
 
 		if (penalty <= perfectpenalty)
 		{
-			bestpenalty = penalty;
 			lowsplit = i;
 			break;
 		}
diff --git a/src/backend/access/spgist/spgtextproc.c b/src/backend/access/spgist/spgtextproc.c
index b5ec81937c..08972e83c6 100644
--- a/src/backend/access/spgist/spgtextproc.c
+++ b/src/backend/access/spgist/spgtextproc.c
@@ -187,7 +187,6 @@ spg_text_choose(PG_FUNCTION_ARGS)
 	char	   *inStr = VARDATA_ANY(inText);
 	int			inSize = VARSIZE_ANY_EXHDR(inText);
 	char	   *prefixStr = NULL;
-	int			prefixSize = 0;
 	int			commonLen = 0;
 	int16		nodeChar = 0;
 	int			i = 0;
@@ -196,6 +195,7 @@ spg_text_choose(PG_FUNCTION_ARGS)
 	if (in->hasPrefix)
 	{
 		text	   *prefixText = DatumGetTextPP(in->prefixDatum);
+	    int			prefixSize;
 
 		prefixStr = VARDATA_ANY(prefixText);
 		prefixSize = VARSIZE_ANY_EXHDR(prefixText);
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 7621fc05e2..1491b047ed 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -10825,7 +10825,6 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 	FILE	   *fp;
 	char		ch;
 	int			seconds_before_warning;
-	int			waits = 0;
 	bool		reported_waiting = false;
 	char	   *remaining;
 	char	   *ptr;
@@ -11146,6 +11145,8 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 		((!backup_started_in_recovery && XLogArchivingActive()) ||
 		 (backup_started_in_recovery && XLogArchivingAlways())))
 	{
+	    int			waits;
+
 		XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
 		XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
 
diff --git a/src/backend/catalog/storage.c b/src/backend/catalog/storage.c
index fddfbf1d8c..3f48a44e66 100644
--- a/src/backend/catalog/storage.c
+++ b/src/backend/catalog/storage.c
@@ -434,7 +434,6 @@ smgrDoPendingDeletes(bool isCommit)
 	PendingRelDelete *prev;
 	PendingRelDelete *next;
 	int			nrels = 0,
-				i = 0,
 				maxrels = 0;
 	SMgrRelation *srels = NULL;
 
@@ -483,6 +482,8 @@ smgrDoPendingDeletes(bool isCommit)
 
 	if (nrels > 0)
 	{
+		int i;
+
 		smgrdounlinkall(srels, nrels, false);
 
 		for (i = 0; i < nrels; i++)
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index c1911411d0..37e8a61c4b 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -1633,12 +1633,7 @@ generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx,
 		if (AttributeNumberIsValid(attnum))
 		{
 			/* Simple index column */
-			char	   *attname;
-
-			attname = get_attname(indrelid, attnum, false);
-			keycoltype = get_atttype(indrelid, attnum);
-
-			iparam->name = attname;
+			iparam->name = get_attname(indrelid, attnum, false);
 			iparam->expr = NULL;
 		}
 		else
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index ffcb54968f..1dd57d9162 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -878,7 +878,7 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
 {
 	char	   *cursor = logbuffer;
 	int			count = *bytes_in_logbuffer;
-	int			dest = LOG_DESTINATION_STDERR;
+	int			dest;
 
 	/* While we have enough for a header, process data... */
 	while (count >= (int) (offsetof(PipeProtoHeader, data) + 1))
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index f45a619deb..df4030f626 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -2821,7 +2821,6 @@ CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 {
 	ProcArrayStruct *arrayP = procArray;
 	int			index;
-	pid_t		pid = 0;
 
 	/* tell all backends to die */
 	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
@@ -2834,6 +2833,7 @@ CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 		if (databaseid == InvalidOid || proc->databaseId == databaseid)
 		{
 			VirtualTransactionId procvxid;
+	        pid_t		pid;
 
 			GET_VXID_FROM_PGPROC(procvxid, *proc);
 
diff --git a/src/backend/tsearch/spell.c b/src/backend/tsearch/spell.c
index 8aab96d3b0..7091fb8e04 100644
--- a/src/backend/tsearch/spell.c
+++ b/src/backend/tsearch/spell.c
@@ -1710,7 +1710,6 @@ void
 NISortDictionary(IspellDict *Conf)
 {
 	int			i;
-	int			naffix = 0;
 	int			curaffix;
 
 	/* compress affixes */
@@ -1760,6 +1759,8 @@ NISortDictionary(IspellDict *Conf)
 	/* Otherwise fill Conf->AffixData here */
 	else
 	{
+	    int			naffix;
+
 		/* Count the number of different flags used in the dictionary */
 		qsort((void *) Conf->Spell, Conf->nspell, sizeof(SPELL *),
 			  cmpspellaffix);
@@ -1879,7 +1880,6 @@ mkANode(IspellDict *Conf, int low, int high, int level, int type)
 		data->naff = naff;
 		data->aff = (AFFIX **) cpalloc(sizeof(AFFIX *) * naff);
 		memcpy(data->aff, aff, sizeof(AFFIX *) * naff);
-		naff = 0;
 	}
 
 	pfree(aff);
@@ -2124,7 +2124,6 @@ CheckAffix(const char *word, size_t len, AFFIX *Affix, int flagflags, char *neww
 	}
 	else
 	{
-		int			err;
 		pg_wchar   *data;
 		size_t		data_len;
 		int			newword_len;
@@ -2134,7 +2133,7 @@ CheckAffix(const char *word, size_t len, AFFIX *Affix, int flagflags, char *neww
 		data = (pg_wchar *) palloc((newword_len + 1) * sizeof(pg_wchar));
 		data_len = pg_mb2wchar_with_len(newword, data, newword_len);
 
-		if (!(err = pg_regexec(&(Affix->reg.regex), data, data_len, 0, NULL, 0, NULL, 0)))
+		if (!pg_regexec(&(Affix->reg.regex), data, data_len, 0, NULL, 0, NULL, 0))
 		{
 			pfree(data);
 			return newword;
diff --git a/src/backend/tsearch/to_tsany.c b/src/backend/tsearch/to_tsany.c
index e7cd6264db..3304066b94 100644
--- a/src/backend/tsearch/to_tsany.c
+++ b/src/backend/tsearch/to_tsany.c
@@ -480,13 +480,7 @@ add_to_tsvector(void *_state, char *elem_value, int elem_len)
 static void
 pushval_morph(Datum opaque, TSQueryParserState state, char *strval, int lenval, int16 weight, bool prefix)
 {
-	int32		count = 0;
 	ParsedText	prs;
-	uint32		variant,
-				pos = 0,
-				cntvar = 0,
-				cntpos = 0,
-				cnt = 0;
 	MorphOpaque *data = (MorphOpaque *) DatumGetPointer(opaque);
 
 	prs.lenwords = 4;
@@ -498,6 +492,13 @@ pushval_morph(Datum opaque, TSQueryParserState state, char *strval, int lenval,
 
 	if (prs.curwords > 0)
 	{
+	    int32	count = 0;
+	    uint32	variant,
+				pos = 0,
+				cntvar = 0,
+				cntpos = 0,
+				cnt = 0;
+
 		while (count < prs.curwords)
 		{
 			/*
diff --git a/src/backend/tsearch/wparser_def.c b/src/backend/tsearch/wparser_def.c
index 898466fcef..66eeb55993 100644
--- a/src/backend/tsearch/wparser_def.c
+++ b/src/backend/tsearch/wparser_def.c
@@ -2133,8 +2133,8 @@ mark_hl_fragments(HeadlineParsedText *prs, TSQuery query, int highlight,
 				maxstretch,
 				posmarker;
 
-	int32		startpos = 0,
-				endpos = 0,
+	int32		startpos,
+				endpos,
 				p = 0,
 				q = 0;
 
diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c
index 7a4a5aaa86..e2a1d06bc5 100644
--- a/src/backend/utils/adt/arrayfuncs.c
+++ b/src/backend/utils/adt/arrayfuncs.c
@@ -2787,7 +2787,6 @@ array_set_slice(Datum arraydatum,
 				overheadlen,
 				oldoverheadlen,
 				addedbefore,
-				addedafter,
 				lenbefore,
 				lenafter,
 				itemsbefore,
@@ -2865,7 +2864,7 @@ array_set_slice(Datum arraydatum,
 	memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
 
 	newhasnulls = (ARR_HASNULL(array) || ARR_HASNULL(srcArray));
-	addedbefore = addedafter = 0;
+	addedbefore = 0;
 
 	/*
 	 * Check subscripts
@@ -2893,8 +2892,7 @@ array_set_slice(Datum arraydatum,
 		{
 			if (lowerIndx[0] > (dim[0] + lb[0]))
 				newhasnulls = true; /* will insert nulls */
-			addedafter = upperIndx[0] - (dim[0] + lb[0]) + 1;
-			dim[0] += addedafter;
+			dim[0] += upperIndx[0] - (dim[0] + lb[0]) + 1;
 		}
 	}
 	else
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index 95f7d0538e..2a30ae4c69 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -4931,7 +4931,7 @@ static char *
 int_to_roman(int number)
 {
 	int			len = 0,
-				num = 0;
+				num;
 	char	   *p = NULL,
 			   *result,
 				numstr[12];
diff --git a/src/backend/utils/adt/tsrank.c b/src/backend/utils/adt/tsrank.c
index f4b0200f1e..e680f649ef 100644
--- a/src/backend/utils/adt/tsrank.c
+++ b/src/backend/utils/adt/tsrank.c
@@ -854,7 +854,7 @@ calc_rank_cd(const float4 *arrdata, TSVector txt, TSQuery query, int method)
 	double		invws[lengthof(weights)];
 	double		SumDist = 0.0,
 				PrevExtPos = 0.0,
-				CurExtPos = 0.0;
+				CurExtPos;
 	int			NExtent = 0;
 	QueryRepresentation qr;
 
diff --git a/src/backend/utils/adt/tsvector_op.c b/src/backend/utils/adt/tsvector_op.c
index 24525879b7..89913ad8fb 100644
--- a/src/backend/utils/adt/tsvector_op.c
+++ b/src/backend/utils/adt/tsvector_op.c
@@ -1263,7 +1263,7 @@ checkcondition_str(void *checkval, QueryOperand *val, ExecPhraseData *data)
 	WordEntry  *StopLow = chkval->arrb;
 	WordEntry  *StopHigh = chkval->arre;
 	WordEntry  *StopMiddle = StopHigh;
-	int			difference = -1;
+	int			difference;
 	bool		res = false;
 
 	/* Loop invariant: StopLow <= val < StopHigh */
diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index d02e676aa3..ab84297975 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -2565,7 +2565,6 @@ mergeruns(Tuplesortstate *state)
 				svTape,
 				svRuns,
 				svDummy;
-	int			numTapes;
 	int			numInputTapes;
 
 	Assert(state->status == TSS_BUILDRUNS);
@@ -2606,7 +2605,7 @@ mergeruns(Tuplesortstate *state)
 	 * If we had fewer runs than tapes, refund the memory that we imagined we
 	 * would need for the tape buffers of the unused tapes.
 	 *
-	 * numTapes and numInputTapes reflect the actual number of tapes we will
+	 * numInputTapes reflect the actual number of tapes we will
 	 * use.  Note that the output tape's tape number is maxTapes - 1, so the
 	 * tape numbers of the used tapes are not consecutive, and you cannot just
 	 * loop from 0 to numTapes to visit all used tapes!
@@ -2614,13 +2613,11 @@ mergeruns(Tuplesortstate *state)
 	if (state->Level == 1)
 	{
 		numInputTapes = state->currentRun;
-		numTapes = numInputTapes + 1;
-		FREEMEM(state, (state->maxTapes - numTapes) * TAPE_BUFFER_OVERHEAD);
+		FREEMEM(state, (state->maxTapes - numInputTapes + 1) * TAPE_BUFFER_OVERHEAD);
 	}
 	else
 	{
 		numInputTapes = state->tapeRange;
-		numTapes = state->maxTapes;
 	}
 
 	/*
#11Ranier Vilela
ranier.vf@gmail.com
In reply to: Ranier Vilela (#10)
17 attachment(s)
Re: [PATCH] Redudant initilization

Em sex., 4 de set. de 2020 às 18:20, Ranier Vilela <ranier.vf@gmail.com>
escreveu:

Em sex., 4 de set. de 2020 às 14:40, Tom Lane <tgl@sss.pgh.pa.us>
escreveu:

Bruce Momjian <bruce@momjian.us> writes:

I have to say, I am kind of stumped why compilers do not warn of such
cases, and why we haven't gotten reports about these cases before.

I was just experimenting with clang's "scan-build" tool. It finds
all of the cases you just fixed, and several dozen more beside.
Quite a few are things that, as a matter of style, we should *not*
change, for instance

rewriteHandler.c:2807:5: warning: Value stored to 'outer_reloids' is
never read
outer_reloids =
list_delete_last(outer_reloids);
^
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are some like this, in the analyzes that I did.
Even when it is the last action of the function.

Failing to update the list pointer here would just be asking for bugs.
However, I see some that look like genuine oversights; will go fix.

Thanks for fixing this.

(I'm not sure how much I trust scan-build overall. It produces a
whole bunch of complaints about null pointer dereferences, for instance.
If those aren't 99% false positives, we'd be crashing constantly.
It's also dog-slow. But it might be something to try occasionally.)

I believe it would be very beneficial.

Attached is a patch I made in March/2020, but due to problems,
it was sent but did not make the list.
Would you mind taking a look?
Certainly, if accepted, rebasing would have to be done.

Here it is simplified, splitted and rebased.
Some are bogus, others are interesting.

regards,
Ranier Vilela

Attachments:

fix_redudant_initialization_firstmissingnum_heaptuple.patchapplication/octet-stream; name=fix_redudant_initialization_firstmissingnum_heaptuple.patchDownload
diff --git a/src/backend/access/common/heaptuple.c b/src/backend/access/common/heaptuple.c
index f89769f379..04b27f1e6e 100644
--- a/src/backend/access/common/heaptuple.c
+++ b/src/backend/access/common/heaptuple.c
@@ -736,7 +736,6 @@ expand_tuple(HeapTuple *targetHeapTuple,
 {
 	AttrMissing *attrmiss = NULL;
 	int			attnum;
-	int			firstmissingnum = 0;
 	bool		hasNulls = HeapTupleHasNulls(sourceTuple);
 	HeapTupleHeader targetTHeader;
 	HeapTupleHeader sourceTHeader = sourceTuple->t_data;
@@ -765,6 +764,8 @@ expand_tuple(HeapTuple *targetHeapTuple,
 	if (tupleDesc->constr &&
 		tupleDesc->constr->missing)
 	{
+	    int			firstmissingnum;
+
 		/*
 		 * If there are missing values we want to put them into the tuple.
 		 * Before that we have to compute the extra length for the values
fix_redudant_initialization_offsetnumber_gistutil.patchapplication/octet-stream; name=fix_redudant_initialization_offsetnumber_gistutil.patchDownload
diff --git a/src/backend/access/gist/gistutil.c b/src/backend/access/gist/gistutil.c
index bfda7fbe3d..e3d8899629 100644
--- a/src/backend/access/gist/gistutil.c
+++ b/src/backend/access/gist/gistutil.c
@@ -32,7 +32,7 @@
 void
 gistfillbuffer(Page page, IndexTuple *itup, int len, OffsetNumber off)
 {
-	OffsetNumber l = InvalidOffsetNumber;
+	OffsetNumber l;
 	int			i;
 
 	if (off == InvalidOffsetNumber)
fix_redudant_initialization_formatting.patchapplication/octet-stream; name=fix_redudant_initialization_formatting.patchDownload
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index bf9643ffb4..19745ed7d8 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -4933,7 +4933,7 @@ static char *
 int_to_roman(int number)
 {
 	int			len = 0,
-				num = 0;
+				num;
 	char	   *p = NULL,
 			   *result,
 				numstr[12];
fix_redudant_initialization_syslogger.patchapplication/octet-stream; name=fix_redudant_initialization_syslogger.patchDownload
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index ffcb54968f..1dd57d9162 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -878,7 +878,7 @@ process_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
 {
 	char	   *cursor = logbuffer;
 	int			count = *bytes_in_logbuffer;
-	int			dest = LOG_DESTINATION_STDERR;
+	int			dest;
 
 	/* While we have enough for a header, process data... */
 	while (count >= (int) (offsetof(PipeProtoHeader, data) + 1))
fix_redudant_initialization_arrayfuncs.patchapplication/octet-stream; name=fix_redudant_initialization_arrayfuncs.patchDownload
diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c
index 392445ea03..ac3b68665c 100644
--- a/src/backend/utils/adt/arrayfuncs.c
+++ b/src/backend/utils/adt/arrayfuncs.c
@@ -2809,7 +2809,6 @@ array_set_slice(Datum arraydatum,
 				overheadlen,
 				oldoverheadlen,
 				addedbefore,
-				addedafter,
 				lenbefore,
 				lenafter,
 				itemsbefore,
@@ -2887,7 +2886,7 @@ array_set_slice(Datum arraydatum,
 	memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
 
 	newhasnulls = (ARR_HASNULL(array) || ARR_HASNULL(srcArray));
-	addedbefore = addedafter = 0;
+	addedbefore = 0;
 
 	/*
 	 * Check subscripts
@@ -2915,8 +2914,7 @@ array_set_slice(Datum arraydatum,
 		{
 			if (lowerIndx[0] > (dim[0] + lb[0]))
 				newhasnulls = true; /* will insert nulls */
-			addedafter = upperIndx[0] - (dim[0] + lb[0]) + 1;
-			dim[0] += addedafter;
+			dim[0] += upperIndx[0] - (dim[0] + lb[0]) + 1;
 		}
 	}
 	else
fix_redudant_initialization_bklno_hash.patchapplication/octet-stream; name=fix_redudant_initialization_bklno_hash.patchDownload
diff --git a/src/backend/access/hash/hashsearch.c b/src/backend/access/hash/hashsearch.c
index 995498e48d..4bc4360173 100644
--- a/src/backend/access/hash/hashsearch.c
+++ b/src/backend/access/hash/hashsearch.c
@@ -457,6 +457,7 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 	Page		page;
 	HashPageOpaque opaque;
 	OffsetNumber offnum;
+	BlockNumber blkno;
 	uint16		itemIndex;
 
 	buf = *bufP;
@@ -470,8 +471,6 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 
 	if (ScanDirectionIsForward(dir))
 	{
-		BlockNumber prev_blkno = InvalidBlockNumber;
-
 		for (;;)
 		{
 			/* new page, locate starting position by binary search */
@@ -496,9 +495,9 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 			 */
 			if (so->currPos.buf == so->hashso_bucket_buf ||
 				so->currPos.buf == so->hashso_split_bucket_buf)
-				prev_blkno = InvalidBlockNumber;
+				blkno = InvalidBlockNumber;
 			else
-				prev_blkno = opaque->hasho_prevblkno;
+				blkno = opaque->hasho_prevblkno;
 
 			_hash_readnext(scan, &buf, &page, &opaque);
 			if (BufferIsValid(buf))
@@ -516,7 +515,7 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 				 * _hash_kill_items to be called for the old page after this
 				 * function returns.
 				 */
-				so->currPos.prevPage = prev_blkno;
+				so->currPos.prevPage = blkno;
 				so->currPos.nextPage = InvalidBlockNumber;
 				so->currPos.buf = buf;
 				return false;
@@ -529,8 +528,6 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 	}
 	else
 	{
-		BlockNumber next_blkno = InvalidBlockNumber;
-
 		for (;;)
 		{
 			/* new page, locate starting position by binary search */
@@ -551,7 +548,9 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 
 			if (so->currPos.buf == so->hashso_bucket_buf ||
 				so->currPos.buf == so->hashso_split_bucket_buf)
-				next_blkno = opaque->hasho_nextblkno;
+				blkno = opaque->hasho_nextblkno;
+			else
+				blkno = InvalidBlockNumber;
 
 			_hash_readprev(scan, &buf, &page, &opaque);
 			if (BufferIsValid(buf))
@@ -570,7 +569,7 @@ _hash_readpage(IndexScanDesc scan, Buffer *bufP, ScanDirection dir)
 				 * function returns.
 				 */
 				so->currPos.prevPage = InvalidBlockNumber;
-				so->currPos.nextPage = next_blkno;
+				so->currPos.nextPage = blkno;
 				so->currPos.buf = buf;
 				return false;
 			}
fix_redudant_initialization_parse_utilcmd.patchapplication/octet-stream; name=fix_redudant_initialization_parse_utilcmd.patchDownload
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index ec944371dd..03f711ccd0 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -1671,13 +1671,9 @@ generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx,
 		if (AttributeNumberIsValid(attnum))
 		{
 			/* Simple index column */
-			char	   *attname;
-
-			attname = get_attname(indrelid, attnum, false);
-			keycoltype = get_atttype(indrelid, attnum);
-
-			iparam->name = attname;
+			iparam->name = get_attname(indrelid, attnum, false);
 			iparam->expr = NULL;
+			keycoltype = get_atttype(indrelid, attnum);
 		}
 		else
 		{
@@ -1706,7 +1702,6 @@ generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx,
 
 			iparam->name = NULL;
 			iparam->expr = indexkey;
-
 			keycoltype = exprType(indexkey);
 		}
fix_redudant_initialization_procarray.patchapplication/octet-stream; name=fix_redudant_initialization_procarray.patchDownload
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index a023090fbb..ca34e9ee8b 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -3433,7 +3433,6 @@ CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 {
 	ProcArrayStruct *arrayP = procArray;
 	int			index;
-	pid_t		pid = 0;
 
 	/* tell all backends to die */
 	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
@@ -3446,6 +3445,7 @@ CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending)
 		if (databaseid == InvalidOid || proc->databaseId == databaseid)
 		{
 			VirtualTransactionId procvxid;
+	        pid_t		pid;
 
 			GET_VXID_FROM_PGPROC(procvxid, *proc);
fix_redudant_initialization_status_nbtsearch.patchapplication/octet-stream; name=fix_redudant_initialization_status_nbtsearch.patchDownload
diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c
index 28dc196b55..defa71229a 100644
--- a/src/backend/access/nbtree/nbtsearch.c
+++ b/src/backend/access/nbtree/nbtsearch.c
@@ -860,7 +860,6 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
 	ScanKeyData notnullkeys[INDEX_MAX_KEYS];
 	int			keysCount = 0;
 	int			i;
-	bool		status = true;
 	StrategyNumber strat_total;
 	BTScanPosItem *currItem;
 	BlockNumber blkno;
@@ -890,6 +889,8 @@ _bt_first(IndexScanDesc scan, ScanDirection dir)
 	 */
 	if (scan->parallel_scan != NULL)
 	{
+		bool	    status;
+
 		status = _bt_parallel_seize(scan, &blkno);
 		if (!status)
 			return false;
@@ -1858,7 +1859,7 @@ _bt_steppage(IndexScanDesc scan, ScanDirection dir)
 {
 	BTScanOpaque so = (BTScanOpaque) scan->opaque;
 	BlockNumber blkno = InvalidBlockNumber;
-	bool		status = true;
+   bool	    status;
 
 	Assert(BTScanPosIsValid(so->currPos));
 
@@ -1967,7 +1968,7 @@ _bt_readnextpage(IndexScanDesc scan, BlockNumber blkno, ScanDirection dir)
 	Relation	rel;
 	Page		page;
 	BTPageOpaque opaque;
-	bool		status = true;
+	bool	    status;
 
 	rel = scan->indexRelation;
fix_redudant_initialization_storage.patchapplication/octet-stream; name=fix_redudant_initialization_storage.patchDownload
diff --git a/src/backend/catalog/storage.c b/src/backend/catalog/storage.c
index 9e6e6c42d3..3c484651c0 100644
--- a/src/backend/catalog/storage.c
+++ b/src/backend/catalog/storage.c
@@ -599,7 +599,6 @@ smgrDoPendingDeletes(bool isCommit)
 	PendingRelDelete *prev;
 	PendingRelDelete *next;
 	int			nrels = 0,
-				i = 0,
 				maxrels = 0;
 	SMgrRelation *srels = NULL;
 
@@ -648,6 +647,8 @@ smgrDoPendingDeletes(bool isCommit)
 
 	if (nrels > 0)
 	{
+		int		i;
+
 		smgrdounlinkall(srels, nrels, false);
 
 		for (i = 0; i < nrels; i++)
fix_redudant_initialization_spell.patchapplication/octet-stream; name=fix_redudant_initialization_spell.patchDownload
diff --git a/src/backend/tsearch/spell.c b/src/backend/tsearch/spell.c
index 49735bc06a..5d5468a13e 100644
--- a/src/backend/tsearch/spell.c
+++ b/src/backend/tsearch/spell.c
@@ -1710,7 +1710,6 @@ void
 NISortDictionary(IspellDict *Conf)
 {
 	int			i;
-	int			naffix = 0;
 	int			curaffix;
 
 	/* compress affixes */
@@ -1760,6 +1759,8 @@ NISortDictionary(IspellDict *Conf)
 	/* Otherwise fill Conf->AffixData here */
 	else
 	{
+	    int			naffix;
+		
 		/* Count the number of different flags used in the dictionary */
 		qsort((void *) Conf->Spell, Conf->nspell, sizeof(SPELL *),
 			  cmpspellaffix);
fix_redudant_initialization_to_tsany.patchapplication/octet-stream; name=fix_redudant_initialization_to_tsany.patchDownload
diff --git a/src/backend/tsearch/to_tsany.c b/src/backend/tsearch/to_tsany.c
index e7cd6264db..81ee5569b1 100644
--- a/src/backend/tsearch/to_tsany.c
+++ b/src/backend/tsearch/to_tsany.c
@@ -480,13 +480,7 @@ add_to_tsvector(void *_state, char *elem_value, int elem_len)
 static void
 pushval_morph(Datum opaque, TSQueryParserState state, char *strval, int lenval, int16 weight, bool prefix)
 {
-	int32		count = 0;
 	ParsedText	prs;
-	uint32		variant,
-				pos = 0,
-				cntvar = 0,
-				cntpos = 0,
-				cnt = 0;
 	MorphOpaque *data = (MorphOpaque *) DatumGetPointer(opaque);
 
 	prs.lenwords = 4;
@@ -498,6 +492,13 @@ pushval_morph(Datum opaque, TSQueryParserState state, char *strval, int lenval,
 
 	if (prs.curwords > 0)
 	{
+		int32	count = 0;
+	    uint32	variant,
+				pos = 0,
+				cntvar = 0,
+				cntpos = 0,
+				cnt = 0;
+
 		while (count < prs.curwords)
 		{
 			/*
fix_redudant_initialization_tsrank.patchapplication/octet-stream; name=fix_redudant_initialization_tsrank.patchDownload
diff --git a/src/backend/utils/adt/tsrank.c b/src/backend/utils/adt/tsrank.c
index c88ebfc7d4..826dd30c4f 100644
--- a/src/backend/utils/adt/tsrank.c
+++ b/src/backend/utils/adt/tsrank.c
@@ -858,7 +858,7 @@ calc_rank_cd(const float4 *arrdata, TSVector txt, TSQuery query, int method)
 	double		invws[lengthof(weights)];
 	double		SumDist = 0.0,
 				PrevExtPos = 0.0,
-				CurExtPos = 0.0;
+				CurExtPos;
 	int			NExtent = 0;
 	QueryRepresentation qr;
fix_redudant_initialization_tuplesort.patchapplication/octet-stream; name=fix_redudant_initialization_tuplesort.patchDownload
diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index 3c49476483..6984d4d37a 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -2738,7 +2738,6 @@ mergeruns(Tuplesortstate *state)
 				svTape,
 				svRuns,
 				svDummy;
-	int			numTapes;
 	int			numInputTapes;
 
 	Assert(state->status == TSS_BUILDRUNS);
@@ -2778,7 +2777,7 @@ mergeruns(Tuplesortstate *state)
 	 * If we had fewer runs than tapes, refund the memory that we imagined we
 	 * would need for the tape buffers of the unused tapes.
 	 *
-	 * numTapes and numInputTapes reflect the actual number of tapes we will
+	 * numInputTapes reflect the actual number of tapes we will
 	 * use.  Note that the output tape's tape number is maxTapes - 1, so the
 	 * tape numbers of the used tapes are not consecutive, and you cannot just
 	 * loop from 0 to numTapes to visit all used tapes!
@@ -2786,13 +2785,11 @@ mergeruns(Tuplesortstate *state)
 	if (state->Level == 1)
 	{
 		numInputTapes = state->currentRun;
-		numTapes = numInputTapes + 1;
-		FREEMEM(state, (state->maxTapes - numTapes) * TAPE_BUFFER_OVERHEAD);
+		FREEMEM(state, (state->maxTapes - numInputTapes + 1) * TAPE_BUFFER_OVERHEAD);
 	}
 	else
 	{
 		numInputTapes = state->tapeRange;
-		numTapes = state->maxTapes;
 	}
 
 	/*
fix_redudant_initialization_wparser_def.patchapplication/octet-stream; name=fix_redudant_initialization_wparser_def.patchDownload
diff --git a/src/backend/tsearch/wparser_def.c b/src/backend/tsearch/wparser_def.c
index 7b29062a97..deecce81b1 100644
--- a/src/backend/tsearch/wparser_def.c
+++ b/src/backend/tsearch/wparser_def.c
@@ -2194,8 +2194,8 @@ mark_hl_fragments(HeadlineParsedText *prs, TSQuery query, bool highlightall,
 				maxstretch,
 				posmarker;
 
-	int32		startpos = 0,
-				endpos = 0,
+	int32		startpos,
+				endpos,
 				p = 0,
 				q = 0;
fix_redudant_prefix_spgtextproc.patchapplication/octet-stream; name=fix_redudant_prefix_spgtextproc.patchDownload
diff --git a/src/backend/access/spgist/spgtextproc.c b/src/backend/access/spgist/spgtextproc.c
index b5ec81937c..71c1b6134b 100644
--- a/src/backend/access/spgist/spgtextproc.c
+++ b/src/backend/access/spgist/spgtextproc.c
@@ -186,8 +186,6 @@ spg_text_choose(PG_FUNCTION_ARGS)
 	text	   *inText = DatumGetTextPP(in->datum);
 	char	   *inStr = VARDATA_ANY(inText);
 	int			inSize = VARSIZE_ANY_EXHDR(inText);
-	char	   *prefixStr = NULL;
-	int			prefixSize = 0;
 	int			commonLen = 0;
 	int16		nodeChar = 0;
 	int			i = 0;
@@ -196,6 +194,8 @@ spg_text_choose(PG_FUNCTION_ARGS)
 	if (in->hasPrefix)
 	{
 		text	   *prefixText = DatumGetTextPP(in->prefixDatum);
+	    char	   *prefixStr;
+	    int			prefixSize;
 
 		prefixStr = VARDATA_ANY(prefixText);
 		prefixSize = VARSIZE_ANY_EXHDR(prefixText);
fix_redudant_waits_xlog.patchapplication/octet-stream; name=fix_redudant_waits_xlog.patchDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 09c01ed4ae..9fe981200a 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -11031,7 +11031,6 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 	FILE	   *fp;
 	char		ch;
 	int			seconds_before_warning;
-	int			waits = 0;
 	bool		reported_waiting = false;
 	char	   *remaining;
 	char	   *ptr;
@@ -11352,6 +11351,8 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 		((!backup_started_in_recovery && XLogArchivingActive()) ||
 		 (backup_started_in_recovery && XLogArchivingAlways())))
 	{
+	    int			waits;
+
 		XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
 		XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
#12Tom Lane
tgl@sss.pgh.pa.us
In reply to: Ranier Vilela (#10)
Re: [PATCH] Redudant initilization

Ranier Vilela <ranier.vf@gmail.com> writes:

Attached is a patch I made in March/2020, but due to problems,
it was sent but did not make the list.
Would you mind taking a look?

I applied some of this, but other parts had been overtaken by
events, and there were other changes that I didn't agree with.

A general comment on the sort of "dead store" that I don't think
we should remove is where a function is trying to maintain an
internal invariant, such as "this pointer points past the last
data written to a buffer" or "these two variables are in sync".
If the update happens to be the last one in the function, the
compiler may be able to see that the store is dead ... but IMO
it should just optimize such a store away and not get in the
programmer's face about it. If we manually remove the dead
store then what we've done is broken the invariant, and we'll
pay for that in future bugs and maintenance costs. Somebody
may someday want to add more code after the step in question,
and if they fail to undo the manual optimization then they've
got a bug. Besides which, it's confusing when a function
does something the same way N-1 times and then differently the
N'th time.

regards, tom lane

#13Ranier Vilela
ranier.vf@gmail.com
In reply to: Tom Lane (#12)
Re: [PATCH] Redudant initilization

Em sáb., 5 de set. de 2020 às 14:29, Tom Lane <tgl@sss.pgh.pa.us> escreveu:

Ranier Vilela <ranier.vf@gmail.com> writes:

Attached is a patch I made in March/2020, but due to problems,
it was sent but did not make the list.
Would you mind taking a look?

I applied some of this, but other parts had been overtaken by
events, and there were other changes that I didn't agree with.

I fully agree with your judgment.

A general comment on the sort of "dead store" that I don't think
we should remove is where a function is trying to maintain an
internal invariant, such as "this pointer points past the last
data written to a buffer" or "these two variables are in sync".
If the update happens to be the last one in the function, the
compiler may be able to see that the store is dead ... but IMO
it should just optimize such a store away and not get in the
programmer's face about it. If we manually remove the dead
store then what we've done is broken the invariant, and we'll
pay for that in future bugs and maintenance costs. Somebody
may someday want to add more code after the step in question,
and if they fail to undo the manual optimization then they've
got a bug. Besides which, it's confusing when a function
does something the same way N-1 times and then differently the

N'th time.

Good point.
The last store is a little strange, but the compiler will certainly
optimize.
Maintenance is expensive, and the current code should be the best example.

regards,
Ranier Vilela