* config/i386/i386.c (ix86_expand_prologue): Tighten assert
[official-gcc.git] / gcc / gimple-ssa-store-merging.c
blob0bc4813be3931ea60d1ee5cf1abf16d7226988c3
1 /* GIMPLE store merging pass.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 Contributed by ARM Ltd.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* The purpose of this pass is to combine multiple memory stores of
22 constant values to consecutive memory locations into fewer wider stores.
23 For example, if we have a sequence peforming four byte stores to
24 consecutive memory locations:
25 [p ] := imm1;
26 [p + 1B] := imm2;
27 [p + 2B] := imm3;
28 [p + 3B] := imm4;
29 we can transform this into a single 4-byte store if the target supports it:
30 [p] := imm1:imm2:imm3:imm4 //concatenated immediates according to endianness.
32 The algorithm is applied to each basic block in three phases:
34 1) Scan through the basic block recording constant assignments to
35 destinations that can be expressed as a store to memory of a certain size
36 at a certain bit offset. Record store chains to different bases in a
37 hash_map (m_stores) and make sure to terminate such chains when appropriate
38 (for example when when the stored values get used subsequently).
39 These stores can be a result of structure element initializers, array stores
40 etc. A store_immediate_info object is recorded for every such store.
41 Record as many such assignments to a single base as possible until a
42 statement that interferes with the store sequence is encountered.
44 2) Analyze the chain of stores recorded in phase 1) (i.e. the vector of
45 store_immediate_info objects) and coalesce contiguous stores into
46 merged_store_group objects.
48 For example, given the stores:
49 [p ] := 0;
50 [p + 1B] := 1;
51 [p + 3B] := 0;
52 [p + 4B] := 1;
53 [p + 5B] := 0;
54 [p + 6B] := 0;
55 This phase would produce two merged_store_group objects, one recording the
56 two bytes stored in the memory region [p : p + 1] and another
57 recording the four bytes stored in the memory region [p + 3 : p + 6].
59 3) The merged_store_group objects produced in phase 2) are processed
60 to generate the sequence of wider stores that set the contiguous memory
61 regions to the sequence of bytes that correspond to it. This may emit
62 multiple stores per store group to handle contiguous stores that are not
63 of a size that is a power of 2. For example it can try to emit a 40-bit
64 store as a 32-bit store followed by an 8-bit store.
65 We try to emit as wide stores as we can while respecting STRICT_ALIGNMENT or
66 TARGET_SLOW_UNALIGNED_ACCESS rules.
68 Note on endianness and example:
69 Consider 2 contiguous 16-bit stores followed by 2 contiguous 8-bit stores:
70 [p ] := 0x1234;
71 [p + 2B] := 0x5678;
72 [p + 4B] := 0xab;
73 [p + 5B] := 0xcd;
75 The memory layout for little-endian (LE) and big-endian (BE) must be:
76 p |LE|BE|
77 ---------
78 0 |34|12|
79 1 |12|34|
80 2 |78|56|
81 3 |56|78|
82 4 |ab|ab|
83 5 |cd|cd|
85 To merge these into a single 48-bit merged value 'val' in phase 2)
86 on little-endian we insert stores to higher (consecutive) bitpositions
87 into the most significant bits of the merged value.
88 The final merged value would be: 0xcdab56781234
90 For big-endian we insert stores to higher bitpositions into the least
91 significant bits of the merged value.
92 The final merged value would be: 0x12345678abcd
94 Then, in phase 3), we want to emit this 48-bit value as a 32-bit store
95 followed by a 16-bit store. Again, we must consider endianness when
96 breaking down the 48-bit value 'val' computed above.
97 For little endian we emit:
98 [p] (32-bit) := 0x56781234; // val & 0x0000ffffffff;
99 [p + 4B] (16-bit) := 0xcdab; // (val & 0xffff00000000) >> 32;
101 Whereas for big-endian we emit:
102 [p] (32-bit) := 0x12345678; // (val & 0xffffffff0000) >> 16;
103 [p + 4B] (16-bit) := 0xabcd; // val & 0x00000000ffff; */
105 #include "config.h"
106 #include "system.h"
107 #include "coretypes.h"
108 #include "backend.h"
109 #include "tree.h"
110 #include "gimple.h"
111 #include "builtins.h"
112 #include "fold-const.h"
113 #include "tree-pass.h"
114 #include "ssa.h"
115 #include "gimple-pretty-print.h"
116 #include "alias.h"
117 #include "fold-const.h"
118 #include "params.h"
119 #include "print-tree.h"
120 #include "tree-hash-traits.h"
121 #include "gimple-iterator.h"
122 #include "gimplify.h"
123 #include "stor-layout.h"
124 #include "timevar.h"
125 #include "tree-cfg.h"
126 #include "tree-eh.h"
127 #include "target.h"
128 #include "gimplify-me.h"
129 #include "rtl.h"
130 #include "expr.h" /* For get_bit_range. */
131 #include "selftest.h"
133 /* The maximum size (in bits) of the stores this pass should generate. */
134 #define MAX_STORE_BITSIZE (BITS_PER_WORD)
135 #define MAX_STORE_BYTES (MAX_STORE_BITSIZE / BITS_PER_UNIT)
137 namespace {
139 /* Struct recording the information about a single store of an immediate
140 to memory. These are created in the first phase and coalesced into
141 merged_store_group objects in the second phase. */
143 struct store_immediate_info
145 unsigned HOST_WIDE_INT bitsize;
146 unsigned HOST_WIDE_INT bitpos;
147 unsigned HOST_WIDE_INT bitregion_start;
148 /* This is one past the last bit of the bit region. */
149 unsigned HOST_WIDE_INT bitregion_end;
150 gimple *stmt;
151 unsigned int order;
152 store_immediate_info (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
153 unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
154 gimple *, unsigned int);
157 store_immediate_info::store_immediate_info (unsigned HOST_WIDE_INT bs,
158 unsigned HOST_WIDE_INT bp,
159 unsigned HOST_WIDE_INT brs,
160 unsigned HOST_WIDE_INT bre,
161 gimple *st,
162 unsigned int ord)
163 : bitsize (bs), bitpos (bp), bitregion_start (brs), bitregion_end (bre),
164 stmt (st), order (ord)
168 /* Struct representing a group of stores to contiguous memory locations.
169 These are produced by the second phase (coalescing) and consumed in the
170 third phase that outputs the widened stores. */
172 struct merged_store_group
174 unsigned HOST_WIDE_INT start;
175 unsigned HOST_WIDE_INT width;
176 unsigned HOST_WIDE_INT bitregion_start;
177 unsigned HOST_WIDE_INT bitregion_end;
178 /* The size of the allocated memory for val and mask. */
179 unsigned HOST_WIDE_INT buf_size;
180 unsigned HOST_WIDE_INT align_base;
182 unsigned int align;
183 unsigned int first_order;
184 unsigned int last_order;
186 auto_vec<store_immediate_info *> stores;
187 /* We record the first and last original statements in the sequence because
188 we'll need their vuse/vdef and replacement position. It's easier to keep
189 track of them separately as 'stores' is reordered by apply_stores. */
190 gimple *last_stmt;
191 gimple *first_stmt;
192 unsigned char *val;
193 unsigned char *mask;
195 merged_store_group (store_immediate_info *);
196 ~merged_store_group ();
197 void merge_into (store_immediate_info *);
198 void merge_overlapping (store_immediate_info *);
199 bool apply_stores ();
200 private:
201 void do_merge (store_immediate_info *);
204 /* Debug helper. Dump LEN elements of byte array PTR to FD in hex. */
206 static void
207 dump_char_array (FILE *fd, unsigned char *ptr, unsigned int len)
209 if (!fd)
210 return;
212 for (unsigned int i = 0; i < len; i++)
213 fprintf (fd, "%x ", ptr[i]);
214 fprintf (fd, "\n");
217 /* Shift left the bytes in PTR of SZ elements by AMNT bits, carrying over the
218 bits between adjacent elements. AMNT should be within
219 [0, BITS_PER_UNIT).
220 Example, AMNT = 2:
221 00011111|11100000 << 2 = 01111111|10000000
222 PTR[1] | PTR[0] PTR[1] | PTR[0]. */
224 static void
225 shift_bytes_in_array (unsigned char *ptr, unsigned int sz, unsigned int amnt)
227 if (amnt == 0)
228 return;
230 unsigned char carry_over = 0U;
231 unsigned char carry_mask = (~0U) << (unsigned char) (BITS_PER_UNIT - amnt);
232 unsigned char clear_mask = (~0U) << amnt;
234 for (unsigned int i = 0; i < sz; i++)
236 unsigned prev_carry_over = carry_over;
237 carry_over = (ptr[i] & carry_mask) >> (BITS_PER_UNIT - amnt);
239 ptr[i] <<= amnt;
240 if (i != 0)
242 ptr[i] &= clear_mask;
243 ptr[i] |= prev_carry_over;
248 /* Like shift_bytes_in_array but for big-endian.
249 Shift right the bytes in PTR of SZ elements by AMNT bits, carrying over the
250 bits between adjacent elements. AMNT should be within
251 [0, BITS_PER_UNIT).
252 Example, AMNT = 2:
253 00011111|11100000 >> 2 = 00000111|11111000
254 PTR[0] | PTR[1] PTR[0] | PTR[1]. */
256 static void
257 shift_bytes_in_array_right (unsigned char *ptr, unsigned int sz,
258 unsigned int amnt)
260 if (amnt == 0)
261 return;
263 unsigned char carry_over = 0U;
264 unsigned char carry_mask = ~(~0U << amnt);
266 for (unsigned int i = 0; i < sz; i++)
268 unsigned prev_carry_over = carry_over;
269 carry_over = ptr[i] & carry_mask;
271 carry_over <<= (unsigned char) BITS_PER_UNIT - amnt;
272 ptr[i] >>= amnt;
273 ptr[i] |= prev_carry_over;
277 /* Clear out LEN bits starting from bit START in the byte array
278 PTR. This clears the bits to the *right* from START.
279 START must be within [0, BITS_PER_UNIT) and counts starting from
280 the least significant bit. */
282 static void
283 clear_bit_region_be (unsigned char *ptr, unsigned int start,
284 unsigned int len)
286 if (len == 0)
287 return;
288 /* Clear len bits to the right of start. */
289 else if (len <= start + 1)
291 unsigned char mask = (~(~0U << len));
292 mask = mask << (start + 1U - len);
293 ptr[0] &= ~mask;
295 else if (start != BITS_PER_UNIT - 1)
297 clear_bit_region_be (ptr, start, (start % BITS_PER_UNIT) + 1);
298 clear_bit_region_be (ptr + 1, BITS_PER_UNIT - 1,
299 len - (start % BITS_PER_UNIT) - 1);
301 else if (start == BITS_PER_UNIT - 1
302 && len > BITS_PER_UNIT)
304 unsigned int nbytes = len / BITS_PER_UNIT;
305 memset (ptr, 0, nbytes);
306 if (len % BITS_PER_UNIT != 0)
307 clear_bit_region_be (ptr + nbytes, BITS_PER_UNIT - 1,
308 len % BITS_PER_UNIT);
310 else
311 gcc_unreachable ();
314 /* In the byte array PTR clear the bit region starting at bit
315 START and is LEN bits wide.
316 For regions spanning multiple bytes do this recursively until we reach
317 zero LEN or a region contained within a single byte. */
319 static void
320 clear_bit_region (unsigned char *ptr, unsigned int start,
321 unsigned int len)
323 /* Degenerate base case. */
324 if (len == 0)
325 return;
326 else if (start >= BITS_PER_UNIT)
327 clear_bit_region (ptr + 1, start - BITS_PER_UNIT, len);
328 /* Second base case. */
329 else if ((start + len) <= BITS_PER_UNIT)
331 unsigned char mask = (~0U) << (unsigned char) (BITS_PER_UNIT - len);
332 mask >>= BITS_PER_UNIT - (start + len);
334 ptr[0] &= ~mask;
336 return;
338 /* Clear most significant bits in a byte and proceed with the next byte. */
339 else if (start != 0)
341 clear_bit_region (ptr, start, BITS_PER_UNIT - start);
342 clear_bit_region (ptr + 1, 0, len - (BITS_PER_UNIT - start));
344 /* Whole bytes need to be cleared. */
345 else if (start == 0 && len > BITS_PER_UNIT)
347 unsigned int nbytes = len / BITS_PER_UNIT;
348 /* We could recurse on each byte but we clear whole bytes, so a simple
349 memset will do. */
350 memset (ptr, '\0', nbytes);
351 /* Clear the remaining sub-byte region if there is one. */
352 if (len % BITS_PER_UNIT != 0)
353 clear_bit_region (ptr + nbytes, 0, len % BITS_PER_UNIT);
355 else
356 gcc_unreachable ();
359 /* Write BITLEN bits of EXPR to the byte array PTR at
360 bit position BITPOS. PTR should contain TOTAL_BYTES elements.
361 Return true if the operation succeeded. */
363 static bool
364 encode_tree_to_bitpos (tree expr, unsigned char *ptr, int bitlen, int bitpos,
365 unsigned int total_bytes)
367 unsigned int first_byte = bitpos / BITS_PER_UNIT;
368 tree tmp_int = expr;
369 bool sub_byte_op_p = ((bitlen % BITS_PER_UNIT)
370 || (bitpos % BITS_PER_UNIT)
371 || !int_mode_for_size (bitlen, 0).exists ());
373 if (!sub_byte_op_p)
374 return native_encode_expr (tmp_int, ptr + first_byte, total_bytes) != 0;
376 /* LITTLE-ENDIAN
377 We are writing a non byte-sized quantity or at a position that is not
378 at a byte boundary.
379 |--------|--------|--------| ptr + first_byte
381 xxx xxxxxxxx xxx< bp>
382 |______EXPR____|
384 First native_encode_expr EXPR into a temporary buffer and shift each
385 byte in the buffer by 'bp' (carrying the bits over as necessary).
386 |00000000|00xxxxxx|xxxxxxxx| << bp = |000xxxxx|xxxxxxxx|xxx00000|
387 <------bitlen---->< bp>
388 Then we clear the destination bits:
389 |---00000|00000000|000-----| ptr + first_byte
390 <-------bitlen--->< bp>
392 Finally we ORR the bytes of the shifted EXPR into the cleared region:
393 |---xxxxx||xxxxxxxx||xxx-----| ptr + first_byte.
395 BIG-ENDIAN
396 We are writing a non byte-sized quantity or at a position that is not
397 at a byte boundary.
398 ptr + first_byte |--------|--------|--------|
400 <bp >xxx xxxxxxxx xxx
401 |_____EXPR_____|
403 First native_encode_expr EXPR into a temporary buffer and shift each
404 byte in the buffer to the right by (carrying the bits over as necessary).
405 We shift by as much as needed to align the most significant bit of EXPR
406 with bitpos:
407 |00xxxxxx|xxxxxxxx| >> 3 = |00000xxx|xxxxxxxx|xxxxx000|
408 <---bitlen----> <bp ><-----bitlen----->
409 Then we clear the destination bits:
410 ptr + first_byte |-----000||00000000||00000---|
411 <bp ><-------bitlen----->
413 Finally we ORR the bytes of the shifted EXPR into the cleared region:
414 ptr + first_byte |---xxxxx||xxxxxxxx||xxx-----|.
415 The awkwardness comes from the fact that bitpos is counted from the
416 most significant bit of a byte. */
418 /* We must be dealing with fixed-size data at this point, since the
419 total size is also fixed. */
420 fixed_size_mode mode = as_a <fixed_size_mode> (TYPE_MODE (TREE_TYPE (expr)));
421 /* Allocate an extra byte so that we have space to shift into. */
422 unsigned int byte_size = GET_MODE_SIZE (mode) + 1;
423 unsigned char *tmpbuf = XALLOCAVEC (unsigned char, byte_size);
424 memset (tmpbuf, '\0', byte_size);
425 /* The store detection code should only have allowed constants that are
426 accepted by native_encode_expr. */
427 if (native_encode_expr (expr, tmpbuf, byte_size - 1) == 0)
428 gcc_unreachable ();
430 /* The native_encode_expr machinery uses TYPE_MODE to determine how many
431 bytes to write. This means it can write more than
432 ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT bytes (for example
433 write 8 bytes for a bitlen of 40). Skip the bytes that are not within
434 bitlen and zero out the bits that are not relevant as well (that may
435 contain a sign bit due to sign-extension). */
436 unsigned int padding
437 = byte_size - ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT - 1;
438 /* On big-endian the padding is at the 'front' so just skip the initial
439 bytes. */
440 if (BYTES_BIG_ENDIAN)
441 tmpbuf += padding;
443 byte_size -= padding;
445 if (bitlen % BITS_PER_UNIT != 0)
447 if (BYTES_BIG_ENDIAN)
448 clear_bit_region_be (tmpbuf, BITS_PER_UNIT - 1,
449 BITS_PER_UNIT - (bitlen % BITS_PER_UNIT));
450 else
451 clear_bit_region (tmpbuf, bitlen,
452 byte_size * BITS_PER_UNIT - bitlen);
454 /* Left shifting relies on the last byte being clear if bitlen is
455 a multiple of BITS_PER_UNIT, which might not be clear if
456 there are padding bytes. */
457 else if (!BYTES_BIG_ENDIAN)
458 tmpbuf[byte_size - 1] = '\0';
460 /* Clear the bit region in PTR where the bits from TMPBUF will be
461 inserted into. */
462 if (BYTES_BIG_ENDIAN)
463 clear_bit_region_be (ptr + first_byte,
464 BITS_PER_UNIT - 1 - (bitpos % BITS_PER_UNIT), bitlen);
465 else
466 clear_bit_region (ptr + first_byte, bitpos % BITS_PER_UNIT, bitlen);
468 int shift_amnt;
469 int bitlen_mod = bitlen % BITS_PER_UNIT;
470 int bitpos_mod = bitpos % BITS_PER_UNIT;
472 bool skip_byte = false;
473 if (BYTES_BIG_ENDIAN)
475 /* BITPOS and BITLEN are exactly aligned and no shifting
476 is necessary. */
477 if (bitpos_mod + bitlen_mod == BITS_PER_UNIT
478 || (bitpos_mod == 0 && bitlen_mod == 0))
479 shift_amnt = 0;
480 /* |. . . . . . . .|
481 <bp > <blen >.
482 We always shift right for BYTES_BIG_ENDIAN so shift the beginning
483 of the value until it aligns with 'bp' in the next byte over. */
484 else if (bitpos_mod + bitlen_mod < BITS_PER_UNIT)
486 shift_amnt = bitlen_mod + bitpos_mod;
487 skip_byte = bitlen_mod != 0;
489 /* |. . . . . . . .|
490 <----bp--->
491 <---blen---->.
492 Shift the value right within the same byte so it aligns with 'bp'. */
493 else
494 shift_amnt = bitlen_mod + bitpos_mod - BITS_PER_UNIT;
496 else
497 shift_amnt = bitpos % BITS_PER_UNIT;
499 /* Create the shifted version of EXPR. */
500 if (!BYTES_BIG_ENDIAN)
502 shift_bytes_in_array (tmpbuf, byte_size, shift_amnt);
503 if (shift_amnt == 0)
504 byte_size--;
506 else
508 gcc_assert (BYTES_BIG_ENDIAN);
509 shift_bytes_in_array_right (tmpbuf, byte_size, shift_amnt);
510 /* If shifting right forced us to move into the next byte skip the now
511 empty byte. */
512 if (skip_byte)
514 tmpbuf++;
515 byte_size--;
519 /* Insert the bits from TMPBUF. */
520 for (unsigned int i = 0; i < byte_size; i++)
521 ptr[first_byte + i] |= tmpbuf[i];
523 return true;
526 /* Sorting function for store_immediate_info objects.
527 Sorts them by bitposition. */
529 static int
530 sort_by_bitpos (const void *x, const void *y)
532 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
533 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
535 if ((*tmp)->bitpos < (*tmp2)->bitpos)
536 return -1;
537 else if ((*tmp)->bitpos > (*tmp2)->bitpos)
538 return 1;
539 else
540 /* If they are the same let's use the order which is guaranteed to
541 be different. */
542 return (*tmp)->order - (*tmp2)->order;
545 /* Sorting function for store_immediate_info objects.
546 Sorts them by the order field. */
548 static int
549 sort_by_order (const void *x, const void *y)
551 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
552 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
554 if ((*tmp)->order < (*tmp2)->order)
555 return -1;
556 else if ((*tmp)->order > (*tmp2)->order)
557 return 1;
559 gcc_unreachable ();
562 /* Initialize a merged_store_group object from a store_immediate_info
563 object. */
565 merged_store_group::merged_store_group (store_immediate_info *info)
567 start = info->bitpos;
568 width = info->bitsize;
569 bitregion_start = info->bitregion_start;
570 bitregion_end = info->bitregion_end;
571 /* VAL has memory allocated for it in apply_stores once the group
572 width has been finalized. */
573 val = NULL;
574 mask = NULL;
575 unsigned HOST_WIDE_INT align_bitpos = 0;
576 get_object_alignment_1 (gimple_assign_lhs (info->stmt),
577 &align, &align_bitpos);
578 align_base = start - align_bitpos;
579 stores.create (1);
580 stores.safe_push (info);
581 last_stmt = info->stmt;
582 last_order = info->order;
583 first_stmt = last_stmt;
584 first_order = last_order;
585 buf_size = 0;
588 merged_store_group::~merged_store_group ()
590 if (val)
591 XDELETEVEC (val);
594 /* Helper method for merge_into and merge_overlapping to do
595 the common part. */
596 void
597 merged_store_group::do_merge (store_immediate_info *info)
599 bitregion_start = MIN (bitregion_start, info->bitregion_start);
600 bitregion_end = MAX (bitregion_end, info->bitregion_end);
602 unsigned int this_align;
603 unsigned HOST_WIDE_INT align_bitpos = 0;
604 get_object_alignment_1 (gimple_assign_lhs (info->stmt),
605 &this_align, &align_bitpos);
606 if (this_align > align)
608 align = this_align;
609 align_base = info->bitpos - align_bitpos;
612 gimple *stmt = info->stmt;
613 stores.safe_push (info);
614 if (info->order > last_order)
616 last_order = info->order;
617 last_stmt = stmt;
619 else if (info->order < first_order)
621 first_order = info->order;
622 first_stmt = stmt;
626 /* Merge a store recorded by INFO into this merged store.
627 The store is not overlapping with the existing recorded
628 stores. */
630 void
631 merged_store_group::merge_into (store_immediate_info *info)
633 unsigned HOST_WIDE_INT wid = info->bitsize;
634 /* Make sure we're inserting in the position we think we're inserting. */
635 gcc_assert (info->bitpos >= start + width
636 && info->bitregion_start <= bitregion_end);
638 width += wid;
639 do_merge (info);
642 /* Merge a store described by INFO into this merged store.
643 INFO overlaps in some way with the current store (i.e. it's not contiguous
644 which is handled by merged_store_group::merge_into). */
646 void
647 merged_store_group::merge_overlapping (store_immediate_info *info)
649 /* If the store extends the size of the group, extend the width. */
650 if (info->bitpos + info->bitsize > start + width)
651 width += info->bitpos + info->bitsize - (start + width);
653 do_merge (info);
656 /* Go through all the recorded stores in this group in program order and
657 apply their values to the VAL byte array to create the final merged
658 value. Return true if the operation succeeded. */
660 bool
661 merged_store_group::apply_stores ()
663 /* Make sure we have more than one store in the group, otherwise we cannot
664 merge anything. */
665 if (bitregion_start % BITS_PER_UNIT != 0
666 || bitregion_end % BITS_PER_UNIT != 0
667 || stores.length () == 1)
668 return false;
670 stores.qsort (sort_by_order);
671 store_immediate_info *info;
672 unsigned int i;
673 /* Create a buffer of a size that is 2 times the number of bytes we're
674 storing. That way native_encode_expr can write power-of-2-sized
675 chunks without overrunning. */
676 buf_size = 2 * ((bitregion_end - bitregion_start) / BITS_PER_UNIT);
677 val = XNEWVEC (unsigned char, 2 * buf_size);
678 mask = val + buf_size;
679 memset (val, 0, buf_size);
680 memset (mask, ~0U, buf_size);
682 FOR_EACH_VEC_ELT (stores, i, info)
684 unsigned int pos_in_buffer = info->bitpos - bitregion_start;
685 bool ret = encode_tree_to_bitpos (gimple_assign_rhs1 (info->stmt),
686 val, info->bitsize,
687 pos_in_buffer, buf_size);
688 if (dump_file && (dump_flags & TDF_DETAILS))
690 if (ret)
692 fprintf (dump_file, "After writing ");
693 print_generic_expr (dump_file,
694 gimple_assign_rhs1 (info->stmt), 0);
695 fprintf (dump_file, " of size " HOST_WIDE_INT_PRINT_DEC
696 " at position %d the merged region contains:\n",
697 info->bitsize, pos_in_buffer);
698 dump_char_array (dump_file, val, buf_size);
700 else
701 fprintf (dump_file, "Failed to merge stores\n");
703 if (!ret)
704 return false;
705 unsigned char *m = mask + (pos_in_buffer / BITS_PER_UNIT);
706 if (BYTES_BIG_ENDIAN)
707 clear_bit_region_be (m, (BITS_PER_UNIT - 1
708 - (pos_in_buffer % BITS_PER_UNIT)),
709 info->bitsize);
710 else
711 clear_bit_region (m, pos_in_buffer % BITS_PER_UNIT, info->bitsize);
713 return true;
716 /* Structure describing the store chain. */
718 struct imm_store_chain_info
720 /* Doubly-linked list that imposes an order on chain processing.
721 PNXP (prev's next pointer) points to the head of a list, or to
722 the next field in the previous chain in the list.
723 See pass_store_merging::m_stores_head for more rationale. */
724 imm_store_chain_info *next, **pnxp;
725 tree base_addr;
726 auto_vec<store_immediate_info *> m_store_info;
727 auto_vec<merged_store_group *> m_merged_store_groups;
729 imm_store_chain_info (imm_store_chain_info *&inspt, tree b_a)
730 : next (inspt), pnxp (&inspt), base_addr (b_a)
732 inspt = this;
733 if (next)
735 gcc_checking_assert (pnxp == next->pnxp);
736 next->pnxp = &next;
739 ~imm_store_chain_info ()
741 *pnxp = next;
742 if (next)
744 gcc_checking_assert (&next == next->pnxp);
745 next->pnxp = pnxp;
748 bool terminate_and_process_chain ();
749 bool coalesce_immediate_stores ();
750 bool output_merged_store (merged_store_group *);
751 bool output_merged_stores ();
754 const pass_data pass_data_tree_store_merging = {
755 GIMPLE_PASS, /* type */
756 "store-merging", /* name */
757 OPTGROUP_NONE, /* optinfo_flags */
758 TV_GIMPLE_STORE_MERGING, /* tv_id */
759 PROP_ssa, /* properties_required */
760 0, /* properties_provided */
761 0, /* properties_destroyed */
762 0, /* todo_flags_start */
763 TODO_update_ssa, /* todo_flags_finish */
766 class pass_store_merging : public gimple_opt_pass
768 public:
769 pass_store_merging (gcc::context *ctxt)
770 : gimple_opt_pass (pass_data_tree_store_merging, ctxt), m_stores_head ()
774 /* Pass not supported for PDP-endianness, nor for insane hosts
775 or target character sizes where native_{encode,interpret}_expr
776 doesn't work properly. */
777 virtual bool
778 gate (function *)
780 return flag_store_merging
781 && WORDS_BIG_ENDIAN == BYTES_BIG_ENDIAN
782 && CHAR_BIT == 8
783 && BITS_PER_UNIT == 8;
786 virtual unsigned int execute (function *);
788 private:
789 hash_map<tree_operand_hash, struct imm_store_chain_info *> m_stores;
791 /* Form a doubly-linked stack of the elements of m_stores, so that
792 we can iterate over them in a predictable way. Using this order
793 avoids extraneous differences in the compiler output just because
794 of tree pointer variations (e.g. different chains end up in
795 different positions of m_stores, so they are handled in different
796 orders, so they allocate or release SSA names in different
797 orders, and when they get reused, subsequent passes end up
798 getting different SSA names, which may ultimately change
799 decisions when going out of SSA). */
800 imm_store_chain_info *m_stores_head;
802 bool terminate_and_process_all_chains ();
803 bool terminate_all_aliasing_chains (imm_store_chain_info **,
804 bool, gimple *);
805 bool terminate_and_release_chain (imm_store_chain_info *);
806 }; // class pass_store_merging
808 /* Terminate and process all recorded chains. Return true if any changes
809 were made. */
811 bool
812 pass_store_merging::terminate_and_process_all_chains ()
814 bool ret = false;
815 while (m_stores_head)
816 ret |= terminate_and_release_chain (m_stores_head);
817 gcc_assert (m_stores.elements () == 0);
818 gcc_assert (m_stores_head == NULL);
820 return ret;
823 /* Terminate all chains that are affected by the assignment to DEST, appearing
824 in statement STMT and ultimately points to the object BASE. Return true if
825 at least one aliasing chain was terminated. BASE and DEST are allowed to
826 be NULL_TREE. In that case the aliasing checks are performed on the whole
827 statement rather than a particular operand in it. VAR_OFFSET_P signifies
828 whether STMT represents a store to BASE offset by a variable amount.
829 If that is the case we have to terminate any chain anchored at BASE. */
831 bool
832 pass_store_merging::terminate_all_aliasing_chains (imm_store_chain_info
833 **chain_info,
834 bool var_offset_p,
835 gimple *stmt)
837 bool ret = false;
839 /* If the statement doesn't touch memory it can't alias. */
840 if (!gimple_vuse (stmt))
841 return false;
843 /* Check if the assignment destination (BASE) is part of a store chain.
844 This is to catch non-constant stores to destinations that may be part
845 of a chain. */
846 if (chain_info)
848 /* We have a chain at BASE and we're writing to [BASE + <variable>].
849 This can interfere with any of the stores so terminate
850 the chain. */
851 if (var_offset_p)
853 terminate_and_release_chain (*chain_info);
854 ret = true;
856 /* Otherwise go through every store in the chain to see if it
857 aliases with any of them. */
858 else
860 store_immediate_info *info;
861 unsigned int i;
862 FOR_EACH_VEC_ELT ((*chain_info)->m_store_info, i, info)
864 if (ref_maybe_used_by_stmt_p (stmt,
865 gimple_assign_lhs (info->stmt))
866 || stmt_may_clobber_ref_p (stmt,
867 gimple_assign_lhs (info->stmt)))
869 if (dump_file && (dump_flags & TDF_DETAILS))
871 fprintf (dump_file,
872 "stmt causes chain termination:\n");
873 print_gimple_stmt (dump_file, stmt, 0);
875 terminate_and_release_chain (*chain_info);
876 ret = true;
877 break;
883 /* Check for aliasing with all other store chains. */
884 for (imm_store_chain_info *next = m_stores_head, *cur = next; cur; cur = next)
886 next = cur->next;
888 /* We already checked all the stores in chain_info and terminated the
889 chain if necessary. Skip it here. */
890 if (chain_info && (*chain_info) == cur)
891 continue;
893 /* We can't use the base object here as that does not reliably exist.
894 Build a ao_ref from the base object address (if we know the
895 minimum and maximum offset and the maximum size we could improve
896 things here). */
897 ao_ref chain_ref;
898 ao_ref_init_from_ptr_and_size (&chain_ref, cur->base_addr, NULL_TREE);
899 if (ref_maybe_used_by_stmt_p (stmt, &chain_ref)
900 || stmt_may_clobber_ref_p_1 (stmt, &chain_ref))
902 terminate_and_release_chain (cur);
903 ret = true;
907 return ret;
910 /* Helper function. Terminate the recorded chain storing to base object
911 BASE. Return true if the merging and output was successful. The m_stores
912 entry is removed after the processing in any case. */
914 bool
915 pass_store_merging::terminate_and_release_chain (imm_store_chain_info *chain_info)
917 bool ret = chain_info->terminate_and_process_chain ();
918 m_stores.remove (chain_info->base_addr);
919 delete chain_info;
920 return ret;
923 /* Go through the candidate stores recorded in m_store_info and merge them
924 into merged_store_group objects recorded into m_merged_store_groups
925 representing the widened stores. Return true if coalescing was successful
926 and the number of widened stores is fewer than the original number
927 of stores. */
929 bool
930 imm_store_chain_info::coalesce_immediate_stores ()
932 /* Anything less can't be processed. */
933 if (m_store_info.length () < 2)
934 return false;
936 if (dump_file && (dump_flags & TDF_DETAILS))
937 fprintf (dump_file, "Attempting to coalesce %u stores in chain.\n",
938 m_store_info.length ());
940 store_immediate_info *info;
941 unsigned int i;
943 /* Order the stores by the bitposition they write to. */
944 m_store_info.qsort (sort_by_bitpos);
946 info = m_store_info[0];
947 merged_store_group *merged_store = new merged_store_group (info);
949 FOR_EACH_VEC_ELT (m_store_info, i, info)
951 if (dump_file && (dump_flags & TDF_DETAILS))
953 fprintf (dump_file, "Store %u:\nbitsize:" HOST_WIDE_INT_PRINT_DEC
954 " bitpos:" HOST_WIDE_INT_PRINT_DEC " val:\n",
955 i, info->bitsize, info->bitpos);
956 print_generic_expr (dump_file, gimple_assign_rhs1 (info->stmt));
957 fprintf (dump_file, "\n------------\n");
960 if (i == 0)
961 continue;
963 /* |---store 1---|
964 |---store 2---|
965 Overlapping stores. */
966 unsigned HOST_WIDE_INT start = info->bitpos;
967 if (IN_RANGE (start, merged_store->start,
968 merged_store->start + merged_store->width - 1))
970 merged_store->merge_overlapping (info);
971 continue;
974 /* |---store 1---| <gap> |---store 2---|.
975 Gap between stores. Start a new group if there are any gaps
976 between bitregions. */
977 if (info->bitregion_start > merged_store->bitregion_end)
979 /* Try to apply all the stores recorded for the group to determine
980 the bitpattern they write and discard it if that fails.
981 This will also reject single-store groups. */
982 if (!merged_store->apply_stores ())
983 delete merged_store;
984 else
985 m_merged_store_groups.safe_push (merged_store);
987 merged_store = new merged_store_group (info);
989 continue;
992 /* |---store 1---||---store 2---|
993 This store is consecutive to the previous one.
994 Merge it into the current store group. */
995 merged_store->merge_into (info);
998 /* Record or discard the last store group. */
999 if (!merged_store->apply_stores ())
1000 delete merged_store;
1001 else
1002 m_merged_store_groups.safe_push (merged_store);
1004 gcc_assert (m_merged_store_groups.length () <= m_store_info.length ());
1005 bool success
1006 = !m_merged_store_groups.is_empty ()
1007 && m_merged_store_groups.length () < m_store_info.length ();
1009 if (success && dump_file)
1010 fprintf (dump_file, "Coalescing successful!\n"
1011 "Merged into %u stores\n",
1012 m_merged_store_groups.length ());
1014 return success;
1017 /* Return the type to use for the merged stores described by STMTS.
1018 This is needed to get the alias sets right. */
1020 static tree
1021 get_alias_type_for_stmts (auto_vec<gimple *> &stmts)
1023 gimple *stmt;
1024 unsigned int i;
1025 tree lhs = gimple_assign_lhs (stmts[0]);
1026 tree type = reference_alias_ptr_type (lhs);
1028 FOR_EACH_VEC_ELT (stmts, i, stmt)
1030 if (i == 0)
1031 continue;
1033 lhs = gimple_assign_lhs (stmt);
1034 tree type1 = reference_alias_ptr_type (lhs);
1035 if (!alias_ptr_types_compatible_p (type, type1))
1036 return ptr_type_node;
1038 return type;
1041 /* Return the location_t information we can find among the statements
1042 in STMTS. */
1044 static location_t
1045 get_location_for_stmts (auto_vec<gimple *> &stmts)
1047 gimple *stmt;
1048 unsigned int i;
1050 FOR_EACH_VEC_ELT (stmts, i, stmt)
1051 if (gimple_has_location (stmt))
1052 return gimple_location (stmt);
1054 return UNKNOWN_LOCATION;
1057 /* Used to decribe a store resulting from splitting a wide store in smaller
1058 regularly-sized stores in split_group. */
1060 struct split_store
1062 unsigned HOST_WIDE_INT bytepos;
1063 unsigned HOST_WIDE_INT size;
1064 unsigned HOST_WIDE_INT align;
1065 auto_vec<gimple *> orig_stmts;
1066 /* True if there is a single orig stmt covering the whole split store. */
1067 bool orig;
1068 split_store (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
1069 unsigned HOST_WIDE_INT);
1072 /* Simple constructor. */
1074 split_store::split_store (unsigned HOST_WIDE_INT bp,
1075 unsigned HOST_WIDE_INT sz,
1076 unsigned HOST_WIDE_INT al)
1077 : bytepos (bp), size (sz), align (al), orig (false)
1079 orig_stmts.create (0);
1082 /* Record all statements corresponding to stores in GROUP that write to
1083 the region starting at BITPOS and is of size BITSIZE. Record such
1084 statements in STMTS if non-NULL. The stores in GROUP must be sorted by
1085 bitposition. Return INFO if there is exactly one original store
1086 in the range. */
1088 static store_immediate_info *
1089 find_constituent_stmts (struct merged_store_group *group,
1090 vec<gimple *> *stmts,
1091 unsigned int *first,
1092 unsigned HOST_WIDE_INT bitpos,
1093 unsigned HOST_WIDE_INT bitsize)
1095 store_immediate_info *info, *ret = NULL;
1096 unsigned int i;
1097 bool second = false;
1098 bool update_first = true;
1099 unsigned HOST_WIDE_INT end = bitpos + bitsize;
1100 for (i = *first; group->stores.iterate (i, &info); ++i)
1102 unsigned HOST_WIDE_INT stmt_start = info->bitpos;
1103 unsigned HOST_WIDE_INT stmt_end = stmt_start + info->bitsize;
1104 if (stmt_end <= bitpos)
1106 /* BITPOS passed to this function never decreases from within the
1107 same split_group call, so optimize and don't scan info records
1108 which are known to end before or at BITPOS next time.
1109 Only do it if all stores before this one also pass this. */
1110 if (update_first)
1111 *first = i + 1;
1112 continue;
1114 else
1115 update_first = false;
1117 /* The stores in GROUP are ordered by bitposition so if we're past
1118 the region for this group return early. */
1119 if (stmt_start >= end)
1120 return ret;
1122 if (stmts)
1124 stmts->safe_push (info->stmt);
1125 if (ret)
1127 ret = NULL;
1128 second = true;
1131 else if (ret)
1132 return NULL;
1133 if (!second)
1134 ret = info;
1136 return ret;
1139 /* Split a merged store described by GROUP by populating the SPLIT_STORES
1140 vector (if non-NULL) with split_store structs describing the byte offset
1141 (from the base), the bit size and alignment of each store as well as the
1142 original statements involved in each such split group.
1143 This is to separate the splitting strategy from the statement
1144 building/emission/linking done in output_merged_store.
1145 Return number of new stores.
1146 If SPLIT_STORES is NULL, it is just a dry run to count number of
1147 new stores. */
1149 static unsigned int
1150 split_group (merged_store_group *group, bool allow_unaligned,
1151 vec<struct split_store *> *split_stores)
1153 unsigned HOST_WIDE_INT pos = group->bitregion_start;
1154 unsigned HOST_WIDE_INT size = group->bitregion_end - pos;
1155 unsigned HOST_WIDE_INT bytepos = pos / BITS_PER_UNIT;
1156 unsigned HOST_WIDE_INT group_align = group->align;
1157 unsigned HOST_WIDE_INT align_base = group->align_base;
1159 gcc_assert ((size % BITS_PER_UNIT == 0) && (pos % BITS_PER_UNIT == 0));
1161 unsigned int ret = 0, first = 0;
1162 unsigned HOST_WIDE_INT try_pos = bytepos;
1163 group->stores.qsort (sort_by_bitpos);
1165 while (size > 0)
1167 if ((allow_unaligned || group_align <= BITS_PER_UNIT)
1168 && group->mask[try_pos - bytepos] == (unsigned char) ~0U)
1170 /* Skip padding bytes. */
1171 ++try_pos;
1172 size -= BITS_PER_UNIT;
1173 continue;
1176 unsigned HOST_WIDE_INT try_bitpos = try_pos * BITS_PER_UNIT;
1177 unsigned int try_size = MAX_STORE_BITSIZE, nonmasked;
1178 unsigned HOST_WIDE_INT align_bitpos
1179 = (try_bitpos - align_base) & (group_align - 1);
1180 unsigned HOST_WIDE_INT align = group_align;
1181 if (align_bitpos)
1182 align = least_bit_hwi (align_bitpos);
1183 if (!allow_unaligned)
1184 try_size = MIN (try_size, align);
1185 store_immediate_info *info
1186 = find_constituent_stmts (group, NULL, &first, try_bitpos, try_size);
1187 if (info)
1189 /* If there is just one original statement for the range, see if
1190 we can just reuse the original store which could be even larger
1191 than try_size. */
1192 unsigned HOST_WIDE_INT stmt_end
1193 = ROUND_UP (info->bitpos + info->bitsize, BITS_PER_UNIT);
1194 info = find_constituent_stmts (group, NULL, &first, try_bitpos,
1195 stmt_end - try_bitpos);
1196 if (info && info->bitpos >= try_bitpos)
1198 try_size = stmt_end - try_bitpos;
1199 goto found;
1203 /* Approximate store bitsize for the case when there are no padding
1204 bits. */
1205 while (try_size > size)
1206 try_size /= 2;
1207 /* Now look for whole padding bytes at the end of that bitsize. */
1208 for (nonmasked = try_size / BITS_PER_UNIT; nonmasked > 0; --nonmasked)
1209 if (group->mask[try_pos - bytepos + nonmasked - 1]
1210 != (unsigned char) ~0U)
1211 break;
1212 if (nonmasked == 0)
1214 /* If entire try_size range is padding, skip it. */
1215 try_pos += try_size / BITS_PER_UNIT;
1216 size -= try_size;
1217 continue;
1219 /* Otherwise try to decrease try_size if second half, last 3 quarters
1220 etc. are padding. */
1221 nonmasked *= BITS_PER_UNIT;
1222 while (nonmasked <= try_size / 2)
1223 try_size /= 2;
1224 if (!allow_unaligned && group_align > BITS_PER_UNIT)
1226 /* Now look for whole padding bytes at the start of that bitsize. */
1227 unsigned int try_bytesize = try_size / BITS_PER_UNIT, masked;
1228 for (masked = 0; masked < try_bytesize; ++masked)
1229 if (group->mask[try_pos - bytepos + masked] != (unsigned char) ~0U)
1230 break;
1231 masked *= BITS_PER_UNIT;
1232 gcc_assert (masked < try_size);
1233 if (masked >= try_size / 2)
1235 while (masked >= try_size / 2)
1237 try_size /= 2;
1238 try_pos += try_size / BITS_PER_UNIT;
1239 size -= try_size;
1240 masked -= try_size;
1242 /* Need to recompute the alignment, so just retry at the new
1243 position. */
1244 continue;
1248 found:
1249 ++ret;
1251 if (split_stores)
1253 struct split_store *store
1254 = new split_store (try_pos, try_size, align);
1255 info = find_constituent_stmts (group, &store->orig_stmts,
1256 &first, try_bitpos, try_size);
1257 if (info
1258 && info->bitpos >= try_bitpos
1259 && info->bitpos + info->bitsize <= try_bitpos + try_size)
1260 store->orig = true;
1261 split_stores->safe_push (store);
1264 try_pos += try_size / BITS_PER_UNIT;
1265 size -= try_size;
1268 return ret;
1271 /* Given a merged store group GROUP output the widened version of it.
1272 The store chain is against the base object BASE.
1273 Try store sizes of at most MAX_STORE_BITSIZE bits wide and don't output
1274 unaligned stores for STRICT_ALIGNMENT targets or if it's too expensive.
1275 Make sure that the number of statements output is less than the number of
1276 original statements. If a better sequence is possible emit it and
1277 return true. */
1279 bool
1280 imm_store_chain_info::output_merged_store (merged_store_group *group)
1282 unsigned HOST_WIDE_INT start_byte_pos
1283 = group->bitregion_start / BITS_PER_UNIT;
1285 unsigned int orig_num_stmts = group->stores.length ();
1286 if (orig_num_stmts < 2)
1287 return false;
1289 auto_vec<struct split_store *, 32> split_stores;
1290 split_stores.create (0);
1291 bool allow_unaligned
1292 = !STRICT_ALIGNMENT && PARAM_VALUE (PARAM_STORE_MERGING_ALLOW_UNALIGNED);
1293 if (allow_unaligned)
1295 /* If unaligned stores are allowed, see how many stores we'd emit
1296 for unaligned and how many stores we'd emit for aligned stores.
1297 Only use unaligned stores if it allows fewer stores than aligned. */
1298 unsigned aligned_cnt = split_group (group, false, NULL);
1299 unsigned unaligned_cnt = split_group (group, true, NULL);
1300 if (aligned_cnt <= unaligned_cnt)
1301 allow_unaligned = false;
1303 split_group (group, allow_unaligned, &split_stores);
1305 if (split_stores.length () >= orig_num_stmts)
1307 /* We didn't manage to reduce the number of statements. Bail out. */
1308 if (dump_file && (dump_flags & TDF_DETAILS))
1310 fprintf (dump_file, "Exceeded original number of stmts (%u)."
1311 " Not profitable to emit new sequence.\n",
1312 orig_num_stmts);
1314 return false;
1317 gimple_stmt_iterator last_gsi = gsi_for_stmt (group->last_stmt);
1318 gimple_seq seq = NULL;
1319 tree last_vdef, new_vuse;
1320 last_vdef = gimple_vdef (group->last_stmt);
1321 new_vuse = gimple_vuse (group->last_stmt);
1323 gimple *stmt = NULL;
1324 split_store *split_store;
1325 unsigned int i;
1327 tree addr = force_gimple_operand_1 (unshare_expr (base_addr), &seq,
1328 is_gimple_mem_ref_addr, NULL_TREE);
1329 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1331 unsigned HOST_WIDE_INT try_size = split_store->size;
1332 unsigned HOST_WIDE_INT try_pos = split_store->bytepos;
1333 unsigned HOST_WIDE_INT align = split_store->align;
1334 tree dest, src;
1335 location_t loc;
1336 if (split_store->orig)
1338 /* If there is just a single constituent store which covers
1339 the whole area, just reuse the lhs and rhs. */
1340 dest = gimple_assign_lhs (split_store->orig_stmts[0]);
1341 src = gimple_assign_rhs1 (split_store->orig_stmts[0]);
1342 loc = gimple_location (split_store->orig_stmts[0]);
1344 else
1346 tree offset_type
1347 = get_alias_type_for_stmts (split_store->orig_stmts);
1348 loc = get_location_for_stmts (split_store->orig_stmts);
1350 tree int_type = build_nonstandard_integer_type (try_size, UNSIGNED);
1351 int_type = build_aligned_type (int_type, align);
1352 dest = fold_build2 (MEM_REF, int_type, addr,
1353 build_int_cst (offset_type, try_pos));
1354 src = native_interpret_expr (int_type,
1355 group->val + try_pos - start_byte_pos,
1356 group->buf_size);
1357 tree mask
1358 = native_interpret_expr (int_type,
1359 group->mask + try_pos - start_byte_pos,
1360 group->buf_size);
1361 if (!integer_zerop (mask))
1363 tree tem = make_ssa_name (int_type);
1364 tree load_src = unshare_expr (dest);
1365 /* The load might load some or all bits uninitialized,
1366 avoid -W*uninitialized warnings in that case.
1367 As optimization, it would be nice if all the bits are
1368 provably uninitialized (no stores at all yet or previous
1369 store a CLOBBER) we'd optimize away the load and replace
1370 it e.g. with 0. */
1371 TREE_NO_WARNING (load_src) = 1;
1372 stmt = gimple_build_assign (tem, load_src);
1373 gimple_set_location (stmt, loc);
1374 gimple_set_vuse (stmt, new_vuse);
1375 gimple_seq_add_stmt_without_update (&seq, stmt);
1377 /* FIXME: If there is a single chunk of zero bits in mask,
1378 perhaps use BIT_INSERT_EXPR instead? */
1379 stmt = gimple_build_assign (make_ssa_name (int_type),
1380 BIT_AND_EXPR, tem, mask);
1381 gimple_set_location (stmt, loc);
1382 gimple_seq_add_stmt_without_update (&seq, stmt);
1383 tem = gimple_assign_lhs (stmt);
1385 src = wide_int_to_tree (int_type,
1386 wi::bit_and_not (wi::to_wide (src),
1387 wi::to_wide (mask)));
1388 stmt = gimple_build_assign (make_ssa_name (int_type),
1389 BIT_IOR_EXPR, tem, src);
1390 gimple_set_location (stmt, loc);
1391 gimple_seq_add_stmt_without_update (&seq, stmt);
1392 src = gimple_assign_lhs (stmt);
1396 stmt = gimple_build_assign (dest, src);
1397 gimple_set_location (stmt, loc);
1398 gimple_set_vuse (stmt, new_vuse);
1399 gimple_seq_add_stmt_without_update (&seq, stmt);
1401 tree new_vdef;
1402 if (i < split_stores.length () - 1)
1403 new_vdef = make_ssa_name (gimple_vop (cfun), stmt);
1404 else
1405 new_vdef = last_vdef;
1407 gimple_set_vdef (stmt, new_vdef);
1408 SSA_NAME_DEF_STMT (new_vdef) = stmt;
1409 new_vuse = new_vdef;
1412 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1413 delete split_store;
1415 gcc_assert (seq);
1416 if (dump_file)
1418 fprintf (dump_file,
1419 "New sequence of %u stmts to replace old one of %u stmts\n",
1420 split_stores.length (), orig_num_stmts);
1421 if (dump_flags & TDF_DETAILS)
1422 print_gimple_seq (dump_file, seq, 0, TDF_VOPS | TDF_MEMSYMS);
1424 gsi_insert_seq_after (&last_gsi, seq, GSI_SAME_STMT);
1426 return true;
1429 /* Process the merged_store_group objects created in the coalescing phase.
1430 The stores are all against the base object BASE.
1431 Try to output the widened stores and delete the original statements if
1432 successful. Return true iff any changes were made. */
1434 bool
1435 imm_store_chain_info::output_merged_stores ()
1437 unsigned int i;
1438 merged_store_group *merged_store;
1439 bool ret = false;
1440 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_store)
1442 if (output_merged_store (merged_store))
1444 unsigned int j;
1445 store_immediate_info *store;
1446 FOR_EACH_VEC_ELT (merged_store->stores, j, store)
1448 gimple *stmt = store->stmt;
1449 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1450 gsi_remove (&gsi, true);
1451 if (stmt != merged_store->last_stmt)
1453 unlink_stmt_vdef (stmt);
1454 release_defs (stmt);
1457 ret = true;
1460 if (ret && dump_file)
1461 fprintf (dump_file, "Merging successful!\n");
1463 return ret;
1466 /* Coalesce the store_immediate_info objects recorded against the base object
1467 BASE in the first phase and output them.
1468 Delete the allocated structures.
1469 Return true if any changes were made. */
1471 bool
1472 imm_store_chain_info::terminate_and_process_chain ()
1474 /* Process store chain. */
1475 bool ret = false;
1476 if (m_store_info.length () > 1)
1478 ret = coalesce_immediate_stores ();
1479 if (ret)
1480 ret = output_merged_stores ();
1483 /* Delete all the entries we allocated ourselves. */
1484 store_immediate_info *info;
1485 unsigned int i;
1486 FOR_EACH_VEC_ELT (m_store_info, i, info)
1487 delete info;
1489 merged_store_group *merged_info;
1490 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_info)
1491 delete merged_info;
1493 return ret;
1496 /* Return true iff LHS is a destination potentially interesting for
1497 store merging. In practice these are the codes that get_inner_reference
1498 can process. */
1500 static bool
1501 lhs_valid_for_store_merging_p (tree lhs)
1503 tree_code code = TREE_CODE (lhs);
1505 if (code == ARRAY_REF || code == ARRAY_RANGE_REF || code == MEM_REF
1506 || code == COMPONENT_REF || code == BIT_FIELD_REF)
1507 return true;
1509 return false;
1512 /* Return true if the tree RHS is a constant we want to consider
1513 during store merging. In practice accept all codes that
1514 native_encode_expr accepts. */
1516 static bool
1517 rhs_valid_for_store_merging_p (tree rhs)
1519 return native_encode_expr (rhs, NULL,
1520 GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (rhs)))) != 0;
1523 /* Entry point for the pass. Go over each basic block recording chains of
1524 immediate stores. Upon encountering a terminating statement (as defined
1525 by stmt_terminates_chain_p) process the recorded stores and emit the widened
1526 variants. */
1528 unsigned int
1529 pass_store_merging::execute (function *fun)
1531 basic_block bb;
1532 hash_set<gimple *> orig_stmts;
1534 FOR_EACH_BB_FN (bb, fun)
1536 gimple_stmt_iterator gsi;
1537 unsigned HOST_WIDE_INT num_statements = 0;
1538 /* Record the original statements so that we can keep track of
1539 statements emitted in this pass and not re-process new
1540 statements. */
1541 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1543 if (is_gimple_debug (gsi_stmt (gsi)))
1544 continue;
1546 if (++num_statements >= 2)
1547 break;
1550 if (num_statements < 2)
1551 continue;
1553 if (dump_file && (dump_flags & TDF_DETAILS))
1554 fprintf (dump_file, "Processing basic block <%d>:\n", bb->index);
1556 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1558 gimple *stmt = gsi_stmt (gsi);
1560 if (is_gimple_debug (stmt))
1561 continue;
1563 if (gimple_has_volatile_ops (stmt))
1565 /* Terminate all chains. */
1566 if (dump_file && (dump_flags & TDF_DETAILS))
1567 fprintf (dump_file, "Volatile access terminates "
1568 "all chains\n");
1569 terminate_and_process_all_chains ();
1570 continue;
1573 if (gimple_assign_single_p (stmt) && gimple_vdef (stmt)
1574 && !stmt_can_throw_internal (stmt)
1575 && lhs_valid_for_store_merging_p (gimple_assign_lhs (stmt)))
1577 tree lhs = gimple_assign_lhs (stmt);
1578 tree rhs = gimple_assign_rhs1 (stmt);
1580 HOST_WIDE_INT bitsize, bitpos;
1581 unsigned HOST_WIDE_INT bitregion_start = 0;
1582 unsigned HOST_WIDE_INT bitregion_end = 0;
1583 machine_mode mode;
1584 int unsignedp = 0, reversep = 0, volatilep = 0;
1585 tree offset, base_addr;
1586 base_addr
1587 = get_inner_reference (lhs, &bitsize, &bitpos, &offset, &mode,
1588 &unsignedp, &reversep, &volatilep);
1589 if (TREE_CODE (lhs) == COMPONENT_REF
1590 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (lhs, 1)))
1592 get_bit_range (&bitregion_start, &bitregion_end, lhs,
1593 &bitpos, &offset);
1594 if (bitregion_end)
1595 ++bitregion_end;
1597 if (bitsize == 0)
1598 continue;
1600 /* As a future enhancement we could handle stores with the same
1601 base and offset. */
1602 bool invalid = reversep
1603 || ((bitsize > MAX_BITSIZE_MODE_ANY_INT)
1604 && (TREE_CODE (rhs) != INTEGER_CST))
1605 || !rhs_valid_for_store_merging_p (rhs);
1607 /* We do not want to rewrite TARGET_MEM_REFs. */
1608 if (TREE_CODE (base_addr) == TARGET_MEM_REF)
1609 invalid = true;
1610 /* In some cases get_inner_reference may return a
1611 MEM_REF [ptr + byteoffset]. For the purposes of this pass
1612 canonicalize the base_addr to MEM_REF [ptr] and take
1613 byteoffset into account in the bitpos. This occurs in
1614 PR 23684 and this way we can catch more chains. */
1615 else if (TREE_CODE (base_addr) == MEM_REF)
1617 offset_int bit_off, byte_off = mem_ref_offset (base_addr);
1618 bit_off = byte_off << LOG2_BITS_PER_UNIT;
1619 bit_off += bitpos;
1620 if (!wi::neg_p (bit_off) && wi::fits_shwi_p (bit_off))
1622 bitpos = bit_off.to_shwi ();
1623 if (bitregion_end)
1625 bit_off = byte_off << LOG2_BITS_PER_UNIT;
1626 bit_off += bitregion_start;
1627 if (wi::fits_uhwi_p (bit_off))
1629 bitregion_start = bit_off.to_uhwi ();
1630 bit_off = byte_off << LOG2_BITS_PER_UNIT;
1631 bit_off += bitregion_end;
1632 if (wi::fits_uhwi_p (bit_off))
1633 bitregion_end = bit_off.to_uhwi ();
1634 else
1635 bitregion_end = 0;
1637 else
1638 bitregion_end = 0;
1641 else
1642 invalid = true;
1643 base_addr = TREE_OPERAND (base_addr, 0);
1645 /* get_inner_reference returns the base object, get at its
1646 address now. */
1647 else
1649 if (bitpos < 0)
1650 invalid = true;
1651 base_addr = build_fold_addr_expr (base_addr);
1654 if (!bitregion_end)
1656 bitregion_start = ROUND_DOWN (bitpos, BITS_PER_UNIT);
1657 bitregion_end = ROUND_UP (bitpos + bitsize, BITS_PER_UNIT);
1660 if (! invalid
1661 && offset != NULL_TREE)
1663 /* If the access is variable offset then a base
1664 decl has to be address-taken to be able to
1665 emit pointer-based stores to it.
1666 ??? We might be able to get away with
1667 re-using the original base up to the first
1668 variable part and then wrapping that inside
1669 a BIT_FIELD_REF. */
1670 tree base = get_base_address (base_addr);
1671 if (! base
1672 || (DECL_P (base)
1673 && ! TREE_ADDRESSABLE (base)))
1674 invalid = true;
1675 else
1676 base_addr = build2 (POINTER_PLUS_EXPR,
1677 TREE_TYPE (base_addr),
1678 base_addr, offset);
1681 struct imm_store_chain_info **chain_info
1682 = m_stores.get (base_addr);
1684 if (!invalid)
1686 store_immediate_info *info;
1687 if (chain_info)
1689 unsigned int ord = (*chain_info)->m_store_info.length ();
1690 info = new store_immediate_info (bitsize, bitpos,
1691 bitregion_start,
1692 bitregion_end,
1693 stmt, ord);
1694 if (dump_file && (dump_flags & TDF_DETAILS))
1696 fprintf (dump_file,
1697 "Recording immediate store from stmt:\n");
1698 print_gimple_stmt (dump_file, stmt, 0);
1700 (*chain_info)->m_store_info.safe_push (info);
1701 /* If we reach the limit of stores to merge in a chain
1702 terminate and process the chain now. */
1703 if ((*chain_info)->m_store_info.length ()
1704 == (unsigned int)
1705 PARAM_VALUE (PARAM_MAX_STORES_TO_MERGE))
1707 if (dump_file && (dump_flags & TDF_DETAILS))
1708 fprintf (dump_file,
1709 "Reached maximum number of statements"
1710 " to merge:\n");
1711 terminate_and_release_chain (*chain_info);
1713 continue;
1716 /* Store aliases any existing chain? */
1717 terminate_all_aliasing_chains (chain_info, false, stmt);
1718 /* Start a new chain. */
1719 struct imm_store_chain_info *new_chain
1720 = new imm_store_chain_info (m_stores_head, base_addr);
1721 info = new store_immediate_info (bitsize, bitpos,
1722 bitregion_start,
1723 bitregion_end,
1724 stmt, 0);
1725 new_chain->m_store_info.safe_push (info);
1726 m_stores.put (base_addr, new_chain);
1727 if (dump_file && (dump_flags & TDF_DETAILS))
1729 fprintf (dump_file,
1730 "Starting new chain with statement:\n");
1731 print_gimple_stmt (dump_file, stmt, 0);
1732 fprintf (dump_file, "The base object is:\n");
1733 print_generic_expr (dump_file, base_addr);
1734 fprintf (dump_file, "\n");
1737 else
1738 terminate_all_aliasing_chains (chain_info,
1739 offset != NULL_TREE, stmt);
1741 continue;
1744 terminate_all_aliasing_chains (NULL, false, stmt);
1746 terminate_and_process_all_chains ();
1748 return 0;
1751 } // anon namespace
1753 /* Construct and return a store merging pass object. */
1755 gimple_opt_pass *
1756 make_pass_store_merging (gcc::context *ctxt)
1758 return new pass_store_merging (ctxt);
1761 #if CHECKING_P
1763 namespace selftest {
1765 /* Selftests for store merging helpers. */
1767 /* Assert that all elements of the byte arrays X and Y, both of length N
1768 are equal. */
1770 static void
1771 verify_array_eq (unsigned char *x, unsigned char *y, unsigned int n)
1773 for (unsigned int i = 0; i < n; i++)
1775 if (x[i] != y[i])
1777 fprintf (stderr, "Arrays do not match. X:\n");
1778 dump_char_array (stderr, x, n);
1779 fprintf (stderr, "Y:\n");
1780 dump_char_array (stderr, y, n);
1782 ASSERT_EQ (x[i], y[i]);
1786 /* Test shift_bytes_in_array and that it carries bits across between
1787 bytes correctly. */
1789 static void
1790 verify_shift_bytes_in_array (void)
1792 /* byte 1 | byte 0
1793 00011111 | 11100000. */
1794 unsigned char orig[2] = { 0xe0, 0x1f };
1795 unsigned char in[2];
1796 memcpy (in, orig, sizeof orig);
1798 unsigned char expected[2] = { 0x80, 0x7f };
1799 shift_bytes_in_array (in, sizeof (in), 2);
1800 verify_array_eq (in, expected, sizeof (in));
1802 memcpy (in, orig, sizeof orig);
1803 memcpy (expected, orig, sizeof orig);
1804 /* Check that shifting by zero doesn't change anything. */
1805 shift_bytes_in_array (in, sizeof (in), 0);
1806 verify_array_eq (in, expected, sizeof (in));
1810 /* Test shift_bytes_in_array_right and that it carries bits across between
1811 bytes correctly. */
1813 static void
1814 verify_shift_bytes_in_array_right (void)
1816 /* byte 1 | byte 0
1817 00011111 | 11100000. */
1818 unsigned char orig[2] = { 0x1f, 0xe0};
1819 unsigned char in[2];
1820 memcpy (in, orig, sizeof orig);
1821 unsigned char expected[2] = { 0x07, 0xf8};
1822 shift_bytes_in_array_right (in, sizeof (in), 2);
1823 verify_array_eq (in, expected, sizeof (in));
1825 memcpy (in, orig, sizeof orig);
1826 memcpy (expected, orig, sizeof orig);
1827 /* Check that shifting by zero doesn't change anything. */
1828 shift_bytes_in_array_right (in, sizeof (in), 0);
1829 verify_array_eq (in, expected, sizeof (in));
1832 /* Test clear_bit_region that it clears exactly the bits asked and
1833 nothing more. */
1835 static void
1836 verify_clear_bit_region (void)
1838 /* Start with all bits set and test clearing various patterns in them. */
1839 unsigned char orig[3] = { 0xff, 0xff, 0xff};
1840 unsigned char in[3];
1841 unsigned char expected[3];
1842 memcpy (in, orig, sizeof in);
1844 /* Check zeroing out all the bits. */
1845 clear_bit_region (in, 0, 3 * BITS_PER_UNIT);
1846 expected[0] = expected[1] = expected[2] = 0;
1847 verify_array_eq (in, expected, sizeof in);
1849 memcpy (in, orig, sizeof in);
1850 /* Leave the first and last bits intact. */
1851 clear_bit_region (in, 1, 3 * BITS_PER_UNIT - 2);
1852 expected[0] = 0x1;
1853 expected[1] = 0;
1854 expected[2] = 0x80;
1855 verify_array_eq (in, expected, sizeof in);
1858 /* Test verify_clear_bit_region_be that it clears exactly the bits asked and
1859 nothing more. */
1861 static void
1862 verify_clear_bit_region_be (void)
1864 /* Start with all bits set and test clearing various patterns in them. */
1865 unsigned char orig[3] = { 0xff, 0xff, 0xff};
1866 unsigned char in[3];
1867 unsigned char expected[3];
1868 memcpy (in, orig, sizeof in);
1870 /* Check zeroing out all the bits. */
1871 clear_bit_region_be (in, BITS_PER_UNIT - 1, 3 * BITS_PER_UNIT);
1872 expected[0] = expected[1] = expected[2] = 0;
1873 verify_array_eq (in, expected, sizeof in);
1875 memcpy (in, orig, sizeof in);
1876 /* Leave the first and last bits intact. */
1877 clear_bit_region_be (in, BITS_PER_UNIT - 2, 3 * BITS_PER_UNIT - 2);
1878 expected[0] = 0x80;
1879 expected[1] = 0;
1880 expected[2] = 0x1;
1881 verify_array_eq (in, expected, sizeof in);
1885 /* Run all of the selftests within this file. */
1887 void
1888 store_merging_c_tests (void)
1890 verify_shift_bytes_in_array ();
1891 verify_shift_bytes_in_array_right ();
1892 verify_clear_bit_region ();
1893 verify_clear_bit_region_be ();
1896 } // namespace selftest
1897 #endif /* CHECKING_P. */