]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/gimple-ssa-store-merging.c
PR sanitizer/81066
[thirdparty/gcc.git] / gcc / gimple-ssa-store-merging.c
CommitLineData
3d3e04ac 1/* GIMPLE store merging pass.
aad93da1 2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3d3e04ac 3 Contributed by ARM Ltd.
4
5 This file is part of GCC.
6
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.
11
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.
16
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/>. */
20
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.
31
32 The algorithm is applied to each basic block in three phases:
33
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.
43
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.
47
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].
58
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 SLOW_UNALIGNED_ACCESS rules.
67
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;
74
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|
84
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
89
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
93
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;
100
101 Whereas for big-endian we emit:
102 [p] (32-bit) := 0x12345678; // (val & 0xffffffff0000) >> 16;
103 [p + 4B] (16-bit) := 0xabcd; // val & 0x00000000ffff; */
104
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"
427223f1 128#include "gimplify-me.h"
3d9a2fb3 129#include "selftest.h"
3d3e04ac 130
131/* The maximum size (in bits) of the stores this pass should generate. */
132#define MAX_STORE_BITSIZE (BITS_PER_WORD)
133#define MAX_STORE_BYTES (MAX_STORE_BITSIZE / BITS_PER_UNIT)
134
135namespace {
136
137/* Struct recording the information about a single store of an immediate
138 to memory. These are created in the first phase and coalesced into
139 merged_store_group objects in the second phase. */
140
141struct store_immediate_info
142{
143 unsigned HOST_WIDE_INT bitsize;
144 unsigned HOST_WIDE_INT bitpos;
3d3e04ac 145 gimple *stmt;
146 unsigned int order;
f85e7cb7 147 store_immediate_info (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
148 gimple *, unsigned int);
3d3e04ac 149};
150
151store_immediate_info::store_immediate_info (unsigned HOST_WIDE_INT bs,
f85e7cb7 152 unsigned HOST_WIDE_INT bp,
153 gimple *st,
3d3e04ac 154 unsigned int ord)
f85e7cb7 155 : bitsize (bs), bitpos (bp), stmt (st), order (ord)
3d3e04ac 156{
157}
158
159/* Struct representing a group of stores to contiguous memory locations.
160 These are produced by the second phase (coalescing) and consumed in the
161 third phase that outputs the widened stores. */
162
163struct merged_store_group
164{
165 unsigned HOST_WIDE_INT start;
166 unsigned HOST_WIDE_INT width;
167 /* The size of the allocated memory for val. */
168 unsigned HOST_WIDE_INT buf_size;
169
170 unsigned int align;
171 unsigned int first_order;
172 unsigned int last_order;
173
174 auto_vec<struct store_immediate_info *> stores;
175 /* We record the first and last original statements in the sequence because
176 we'll need their vuse/vdef and replacement position. It's easier to keep
177 track of them separately as 'stores' is reordered by apply_stores. */
178 gimple *last_stmt;
179 gimple *first_stmt;
180 unsigned char *val;
181
182 merged_store_group (store_immediate_info *);
183 ~merged_store_group ();
184 void merge_into (store_immediate_info *);
185 void merge_overlapping (store_immediate_info *);
186 bool apply_stores ();
187};
188
189/* Debug helper. Dump LEN elements of byte array PTR to FD in hex. */
190
191static void
192dump_char_array (FILE *fd, unsigned char *ptr, unsigned int len)
193{
194 if (!fd)
195 return;
196
197 for (unsigned int i = 0; i < len; i++)
198 fprintf (fd, "%x ", ptr[i]);
199 fprintf (fd, "\n");
200}
201
3d3e04ac 202/* Shift left the bytes in PTR of SZ elements by AMNT bits, carrying over the
203 bits between adjacent elements. AMNT should be within
204 [0, BITS_PER_UNIT).
205 Example, AMNT = 2:
206 00011111|11100000 << 2 = 01111111|10000000
207 PTR[1] | PTR[0] PTR[1] | PTR[0]. */
208
209static void
210shift_bytes_in_array (unsigned char *ptr, unsigned int sz, unsigned int amnt)
211{
212 if (amnt == 0)
213 return;
214
215 unsigned char carry_over = 0U;
b1c71535 216 unsigned char carry_mask = (~0U) << (unsigned char) (BITS_PER_UNIT - amnt);
3d3e04ac 217 unsigned char clear_mask = (~0U) << amnt;
218
219 for (unsigned int i = 0; i < sz; i++)
220 {
221 unsigned prev_carry_over = carry_over;
b1c71535 222 carry_over = (ptr[i] & carry_mask) >> (BITS_PER_UNIT - amnt);
3d3e04ac 223
224 ptr[i] <<= amnt;
225 if (i != 0)
226 {
227 ptr[i] &= clear_mask;
228 ptr[i] |= prev_carry_over;
229 }
230 }
231}
232
233/* Like shift_bytes_in_array but for big-endian.
234 Shift right the bytes in PTR of SZ elements by AMNT bits, carrying over the
235 bits between adjacent elements. AMNT should be within
236 [0, BITS_PER_UNIT).
237 Example, AMNT = 2:
238 00011111|11100000 >> 2 = 00000111|11111000
239 PTR[0] | PTR[1] PTR[0] | PTR[1]. */
240
241static void
242shift_bytes_in_array_right (unsigned char *ptr, unsigned int sz,
243 unsigned int amnt)
244{
245 if (amnt == 0)
246 return;
247
248 unsigned char carry_over = 0U;
249 unsigned char carry_mask = ~(~0U << amnt);
250
251 for (unsigned int i = 0; i < sz; i++)
252 {
253 unsigned prev_carry_over = carry_over;
b1c71535 254 carry_over = ptr[i] & carry_mask;
3d3e04ac 255
a425d9af 256 carry_over <<= (unsigned char) BITS_PER_UNIT - amnt;
257 ptr[i] >>= amnt;
258 ptr[i] |= prev_carry_over;
3d3e04ac 259 }
260}
261
262/* Clear out LEN bits starting from bit START in the byte array
263 PTR. This clears the bits to the *right* from START.
264 START must be within [0, BITS_PER_UNIT) and counts starting from
265 the least significant bit. */
266
267static void
268clear_bit_region_be (unsigned char *ptr, unsigned int start,
269 unsigned int len)
270{
271 if (len == 0)
272 return;
273 /* Clear len bits to the right of start. */
274 else if (len <= start + 1)
275 {
276 unsigned char mask = (~(~0U << len));
277 mask = mask << (start + 1U - len);
278 ptr[0] &= ~mask;
279 }
280 else if (start != BITS_PER_UNIT - 1)
281 {
282 clear_bit_region_be (ptr, start, (start % BITS_PER_UNIT) + 1);
283 clear_bit_region_be (ptr + 1, BITS_PER_UNIT - 1,
284 len - (start % BITS_PER_UNIT) - 1);
285 }
286 else if (start == BITS_PER_UNIT - 1
287 && len > BITS_PER_UNIT)
288 {
289 unsigned int nbytes = len / BITS_PER_UNIT;
290 for (unsigned int i = 0; i < nbytes; i++)
291 ptr[i] = 0U;
292 if (len % BITS_PER_UNIT != 0)
293 clear_bit_region_be (ptr + nbytes, BITS_PER_UNIT - 1,
294 len % BITS_PER_UNIT);
295 }
296 else
297 gcc_unreachable ();
298}
299
300/* In the byte array PTR clear the bit region starting at bit
301 START and is LEN bits wide.
302 For regions spanning multiple bytes do this recursively until we reach
303 zero LEN or a region contained within a single byte. */
304
305static void
306clear_bit_region (unsigned char *ptr, unsigned int start,
307 unsigned int len)
308{
309 /* Degenerate base case. */
310 if (len == 0)
311 return;
312 else if (start >= BITS_PER_UNIT)
313 clear_bit_region (ptr + 1, start - BITS_PER_UNIT, len);
314 /* Second base case. */
315 else if ((start + len) <= BITS_PER_UNIT)
316 {
b1c71535 317 unsigned char mask = (~0U) << (unsigned char) (BITS_PER_UNIT - len);
3d3e04ac 318 mask >>= BITS_PER_UNIT - (start + len);
319
320 ptr[0] &= ~mask;
321
322 return;
323 }
324 /* Clear most significant bits in a byte and proceed with the next byte. */
325 else if (start != 0)
326 {
327 clear_bit_region (ptr, start, BITS_PER_UNIT - start);
3d6071e9 328 clear_bit_region (ptr + 1, 0, len - (BITS_PER_UNIT - start));
3d3e04ac 329 }
330 /* Whole bytes need to be cleared. */
331 else if (start == 0 && len > BITS_PER_UNIT)
332 {
333 unsigned int nbytes = len / BITS_PER_UNIT;
334 /* We could recurse on each byte but do the loop here to avoid
335 recursing too deep. */
b1c71535 336 memset (ptr, '\0', nbytes);
3d3e04ac 337 /* Clear the remaining sub-byte region if there is one. */
338 if (len % BITS_PER_UNIT != 0)
339 clear_bit_region (ptr + nbytes, 0, len % BITS_PER_UNIT);
340 }
341 else
342 gcc_unreachable ();
343}
344
345/* Write BITLEN bits of EXPR to the byte array PTR at
346 bit position BITPOS. PTR should contain TOTAL_BYTES elements.
347 Return true if the operation succeeded. */
348
349static bool
350encode_tree_to_bitpos (tree expr, unsigned char *ptr, int bitlen, int bitpos,
b1c71535 351 unsigned int total_bytes)
3d3e04ac 352{
353 unsigned int first_byte = bitpos / BITS_PER_UNIT;
354 tree tmp_int = expr;
a425d9af 355 bool sub_byte_op_p = ((bitlen % BITS_PER_UNIT)
356 || (bitpos % BITS_PER_UNIT)
357 || mode_for_size (bitlen, MODE_INT, 0) == BLKmode);
3d3e04ac 358
359 if (!sub_byte_op_p)
b1c71535 360 return (native_encode_expr (tmp_int, ptr + first_byte, total_bytes, 0)
361 != 0);
3d3e04ac 362
363 /* LITTLE-ENDIAN
364 We are writing a non byte-sized quantity or at a position that is not
365 at a byte boundary.
366 |--------|--------|--------| ptr + first_byte
367 ^ ^
368 xxx xxxxxxxx xxx< bp>
369 |______EXPR____|
370
b1c71535 371 First native_encode_expr EXPR into a temporary buffer and shift each
3d3e04ac 372 byte in the buffer by 'bp' (carrying the bits over as necessary).
373 |00000000|00xxxxxx|xxxxxxxx| << bp = |000xxxxx|xxxxxxxx|xxx00000|
374 <------bitlen---->< bp>
375 Then we clear the destination bits:
376 |---00000|00000000|000-----| ptr + first_byte
377 <-------bitlen--->< bp>
378
379 Finally we ORR the bytes of the shifted EXPR into the cleared region:
380 |---xxxxx||xxxxxxxx||xxx-----| ptr + first_byte.
381
382 BIG-ENDIAN
383 We are writing a non byte-sized quantity or at a position that is not
384 at a byte boundary.
385 ptr + first_byte |--------|--------|--------|
386 ^ ^
387 <bp >xxx xxxxxxxx xxx
388 |_____EXPR_____|
389
b1c71535 390 First native_encode_expr EXPR into a temporary buffer and shift each
3d3e04ac 391 byte in the buffer to the right by (carrying the bits over as necessary).
392 We shift by as much as needed to align the most significant bit of EXPR
393 with bitpos:
394 |00xxxxxx|xxxxxxxx| >> 3 = |00000xxx|xxxxxxxx|xxxxx000|
395 <---bitlen----> <bp ><-----bitlen----->
396 Then we clear the destination bits:
397 ptr + first_byte |-----000||00000000||00000---|
398 <bp ><-------bitlen----->
399
400 Finally we ORR the bytes of the shifted EXPR into the cleared region:
401 ptr + first_byte |---xxxxx||xxxxxxxx||xxx-----|.
402 The awkwardness comes from the fact that bitpos is counted from the
403 most significant bit of a byte. */
404
405 /* Allocate an extra byte so that we have space to shift into. */
406 unsigned int byte_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (expr))) + 1;
407 unsigned char *tmpbuf = XALLOCAVEC (unsigned char, byte_size);
b1c71535 408 memset (tmpbuf, '\0', byte_size);
3d3e04ac 409 /* The store detection code should only have allowed constants that are
410 accepted by native_encode_expr. */
a425d9af 411 if (native_encode_expr (expr, tmpbuf, byte_size - 1, 0) == 0)
3d3e04ac 412 gcc_unreachable ();
413
414 /* The native_encode_expr machinery uses TYPE_MODE to determine how many
415 bytes to write. This means it can write more than
416 ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT bytes (for example
417 write 8 bytes for a bitlen of 40). Skip the bytes that are not within
418 bitlen and zero out the bits that are not relevant as well (that may
419 contain a sign bit due to sign-extension). */
420 unsigned int padding
421 = byte_size - ROUND_UP (bitlen, BITS_PER_UNIT) / BITS_PER_UNIT - 1;
a425d9af 422 /* On big-endian the padding is at the 'front' so just skip the initial
423 bytes. */
424 if (BYTES_BIG_ENDIAN)
425 tmpbuf += padding;
426
427 byte_size -= padding;
428
429 if (bitlen % BITS_PER_UNIT != 0)
3d3e04ac 430 {
5e922e43 431 if (BYTES_BIG_ENDIAN)
a425d9af 432 clear_bit_region_be (tmpbuf, BITS_PER_UNIT - 1,
433 BITS_PER_UNIT - (bitlen % BITS_PER_UNIT));
434 else
435 clear_bit_region (tmpbuf, bitlen,
436 byte_size * BITS_PER_UNIT - bitlen);
3d3e04ac 437 }
a425d9af 438 /* Left shifting relies on the last byte being clear if bitlen is
439 a multiple of BITS_PER_UNIT, which might not be clear if
440 there are padding bytes. */
441 else if (!BYTES_BIG_ENDIAN)
442 tmpbuf[byte_size - 1] = '\0';
3d3e04ac 443
444 /* Clear the bit region in PTR where the bits from TMPBUF will be
b1c71535 445 inserted into. */
3d3e04ac 446 if (BYTES_BIG_ENDIAN)
447 clear_bit_region_be (ptr + first_byte,
448 BITS_PER_UNIT - 1 - (bitpos % BITS_PER_UNIT), bitlen);
449 else
450 clear_bit_region (ptr + first_byte, bitpos % BITS_PER_UNIT, bitlen);
451
452 int shift_amnt;
453 int bitlen_mod = bitlen % BITS_PER_UNIT;
454 int bitpos_mod = bitpos % BITS_PER_UNIT;
455
456 bool skip_byte = false;
457 if (BYTES_BIG_ENDIAN)
458 {
459 /* BITPOS and BITLEN are exactly aligned and no shifting
460 is necessary. */
461 if (bitpos_mod + bitlen_mod == BITS_PER_UNIT
462 || (bitpos_mod == 0 && bitlen_mod == 0))
463 shift_amnt = 0;
464 /* |. . . . . . . .|
465 <bp > <blen >.
466 We always shift right for BYTES_BIG_ENDIAN so shift the beginning
467 of the value until it aligns with 'bp' in the next byte over. */
468 else if (bitpos_mod + bitlen_mod < BITS_PER_UNIT)
469 {
470 shift_amnt = bitlen_mod + bitpos_mod;
471 skip_byte = bitlen_mod != 0;
472 }
473 /* |. . . . . . . .|
474 <----bp--->
475 <---blen---->.
476 Shift the value right within the same byte so it aligns with 'bp'. */
477 else
478 shift_amnt = bitlen_mod + bitpos_mod - BITS_PER_UNIT;
479 }
480 else
481 shift_amnt = bitpos % BITS_PER_UNIT;
482
483 /* Create the shifted version of EXPR. */
484 if (!BYTES_BIG_ENDIAN)
b1c71535 485 {
486 shift_bytes_in_array (tmpbuf, byte_size, shift_amnt);
487 if (shift_amnt == 0)
488 byte_size--;
489 }
3d3e04ac 490 else
491 {
492 gcc_assert (BYTES_BIG_ENDIAN);
493 shift_bytes_in_array_right (tmpbuf, byte_size, shift_amnt);
494 /* If shifting right forced us to move into the next byte skip the now
495 empty byte. */
496 if (skip_byte)
497 {
498 tmpbuf++;
499 byte_size--;
500 }
501 }
502
503 /* Insert the bits from TMPBUF. */
504 for (unsigned int i = 0; i < byte_size; i++)
505 ptr[first_byte + i] |= tmpbuf[i];
506
507 return true;
508}
509
510/* Sorting function for store_immediate_info objects.
511 Sorts them by bitposition. */
512
513static int
514sort_by_bitpos (const void *x, const void *y)
515{
516 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
517 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
518
519 if ((*tmp)->bitpos <= (*tmp2)->bitpos)
520 return -1;
521 else if ((*tmp)->bitpos > (*tmp2)->bitpos)
522 return 1;
523
524 gcc_unreachable ();
525}
526
527/* Sorting function for store_immediate_info objects.
528 Sorts them by the order field. */
529
530static int
531sort_by_order (const void *x, const void *y)
532{
533 store_immediate_info *const *tmp = (store_immediate_info * const *) x;
534 store_immediate_info *const *tmp2 = (store_immediate_info * const *) y;
535
536 if ((*tmp)->order < (*tmp2)->order)
537 return -1;
538 else if ((*tmp)->order > (*tmp2)->order)
539 return 1;
540
541 gcc_unreachable ();
542}
543
544/* Initialize a merged_store_group object from a store_immediate_info
545 object. */
546
547merged_store_group::merged_store_group (store_immediate_info *info)
548{
549 start = info->bitpos;
550 width = info->bitsize;
551 /* VAL has memory allocated for it in apply_stores once the group
552 width has been finalized. */
553 val = NULL;
f85e7cb7 554 align = get_object_alignment (gimple_assign_lhs (info->stmt));
3d3e04ac 555 stores.create (1);
556 stores.safe_push (info);
557 last_stmt = info->stmt;
558 last_order = info->order;
559 first_stmt = last_stmt;
560 first_order = last_order;
561 buf_size = 0;
562}
563
564merged_store_group::~merged_store_group ()
565{
566 if (val)
567 XDELETEVEC (val);
568}
569
570/* Merge a store recorded by INFO into this merged store.
571 The store is not overlapping with the existing recorded
572 stores. */
573
574void
575merged_store_group::merge_into (store_immediate_info *info)
576{
577 unsigned HOST_WIDE_INT wid = info->bitsize;
578 /* Make sure we're inserting in the position we think we're inserting. */
579 gcc_assert (info->bitpos == start + width);
580
581 width += wid;
582 gimple *stmt = info->stmt;
583 stores.safe_push (info);
584 if (info->order > last_order)
585 {
586 last_order = info->order;
587 last_stmt = stmt;
588 }
589 else if (info->order < first_order)
590 {
591 first_order = info->order;
592 first_stmt = stmt;
593 }
594}
595
596/* Merge a store described by INFO into this merged store.
597 INFO overlaps in some way with the current store (i.e. it's not contiguous
598 which is handled by merged_store_group::merge_into). */
599
600void
601merged_store_group::merge_overlapping (store_immediate_info *info)
602{
603 gimple *stmt = info->stmt;
604 stores.safe_push (info);
605
606 /* If the store extends the size of the group, extend the width. */
607 if ((info->bitpos + info->bitsize) > (start + width))
608 width += info->bitpos + info->bitsize - (start + width);
609
610 if (info->order > last_order)
611 {
612 last_order = info->order;
613 last_stmt = stmt;
614 }
615 else if (info->order < first_order)
616 {
617 first_order = info->order;
618 first_stmt = stmt;
619 }
620}
621
622/* Go through all the recorded stores in this group in program order and
623 apply their values to the VAL byte array to create the final merged
624 value. Return true if the operation succeeded. */
625
626bool
627merged_store_group::apply_stores ()
628{
629 /* The total width of the stores must add up to a whole number of bytes
630 and start at a byte boundary. We don't support emitting bitfield
631 references for now. Also, make sure we have more than one store
632 in the group, otherwise we cannot merge anything. */
633 if (width % BITS_PER_UNIT != 0
634 || start % BITS_PER_UNIT != 0
635 || stores.length () == 1)
636 return false;
637
638 stores.qsort (sort_by_order);
639 struct store_immediate_info *info;
640 unsigned int i;
641 /* Create a buffer of a size that is 2 times the number of bytes we're
642 storing. That way native_encode_expr can write power-of-2-sized
643 chunks without overrunning. */
b1c71535 644 buf_size = 2 * (ROUND_UP (width, BITS_PER_UNIT) / BITS_PER_UNIT);
3d3e04ac 645 val = XCNEWVEC (unsigned char, buf_size);
646
647 FOR_EACH_VEC_ELT (stores, i, info)
648 {
649 unsigned int pos_in_buffer = info->bitpos - start;
f85e7cb7 650 bool ret = encode_tree_to_bitpos (gimple_assign_rhs1 (info->stmt),
651 val, info->bitsize,
652 pos_in_buffer, buf_size);
3d3e04ac 653 if (dump_file && (dump_flags & TDF_DETAILS))
654 {
655 if (ret)
656 {
657 fprintf (dump_file, "After writing ");
f85e7cb7 658 print_generic_expr (dump_file,
659 gimple_assign_rhs1 (info->stmt), 0);
3d3e04ac 660 fprintf (dump_file, " of size " HOST_WIDE_INT_PRINT_DEC
661 " at position %d the merged region contains:\n",
662 info->bitsize, pos_in_buffer);
663 dump_char_array (dump_file, val, buf_size);
664 }
665 else
666 fprintf (dump_file, "Failed to merge stores\n");
667 }
668 if (!ret)
669 return false;
670 }
671 return true;
672}
673
674/* Structure describing the store chain. */
675
676struct imm_store_chain_info
677{
3a3ba7de 678 /* Doubly-linked list that imposes an order on chain processing.
679 PNXP (prev's next pointer) points to the head of a list, or to
680 the next field in the previous chain in the list.
681 See pass_store_merging::m_stores_head for more rationale. */
682 imm_store_chain_info *next, **pnxp;
f85e7cb7 683 tree base_addr;
3d3e04ac 684 auto_vec<struct store_immediate_info *> m_store_info;
685 auto_vec<merged_store_group *> m_merged_store_groups;
686
3a3ba7de 687 imm_store_chain_info (imm_store_chain_info *&inspt, tree b_a)
688 : next (inspt), pnxp (&inspt), base_addr (b_a)
689 {
690 inspt = this;
691 if (next)
692 {
693 gcc_checking_assert (pnxp == next->pnxp);
694 next->pnxp = &next;
695 }
696 }
697 ~imm_store_chain_info ()
698 {
699 *pnxp = next;
700 if (next)
701 {
702 gcc_checking_assert (&next == next->pnxp);
703 next->pnxp = pnxp;
704 }
705 }
f85e7cb7 706 bool terminate_and_process_chain ();
3d3e04ac 707 bool coalesce_immediate_stores ();
f85e7cb7 708 bool output_merged_store (merged_store_group *);
709 bool output_merged_stores ();
3d3e04ac 710};
711
712const pass_data pass_data_tree_store_merging = {
713 GIMPLE_PASS, /* type */
714 "store-merging", /* name */
715 OPTGROUP_NONE, /* optinfo_flags */
716 TV_GIMPLE_STORE_MERGING, /* tv_id */
717 PROP_ssa, /* properties_required */
718 0, /* properties_provided */
719 0, /* properties_destroyed */
720 0, /* todo_flags_start */
721 TODO_update_ssa, /* todo_flags_finish */
722};
723
724class pass_store_merging : public gimple_opt_pass
725{
726public:
727 pass_store_merging (gcc::context *ctxt)
2d27e5c1 728 : gimple_opt_pass (pass_data_tree_store_merging, ctxt), m_stores_head ()
3d3e04ac 729 {
730 }
731
732 /* Pass not supported for PDP-endianness. */
733 virtual bool
734 gate (function *)
735 {
736 return flag_store_merging && (WORDS_BIG_ENDIAN == BYTES_BIG_ENDIAN);
737 }
738
739 virtual unsigned int execute (function *);
740
741private:
742 hash_map<tree_operand_hash, struct imm_store_chain_info *> m_stores;
743
3a3ba7de 744 /* Form a doubly-linked stack of the elements of m_stores, so that
745 we can iterate over them in a predictable way. Using this order
746 avoids extraneous differences in the compiler output just because
747 of tree pointer variations (e.g. different chains end up in
748 different positions of m_stores, so they are handled in different
749 orders, so they allocate or release SSA names in different
750 orders, and when they get reused, subsequent passes end up
751 getting different SSA names, which may ultimately change
752 decisions when going out of SSA). */
753 imm_store_chain_info *m_stores_head;
754
3d3e04ac 755 bool terminate_and_process_all_chains ();
4de7f8df 756 bool terminate_all_aliasing_chains (imm_store_chain_info **,
f85e7cb7 757 bool, gimple *);
758 bool terminate_and_release_chain (imm_store_chain_info *);
3d3e04ac 759}; // class pass_store_merging
760
761/* Terminate and process all recorded chains. Return true if any changes
762 were made. */
763
764bool
765pass_store_merging::terminate_and_process_all_chains ()
766{
3d3e04ac 767 bool ret = false;
3a3ba7de 768 while (m_stores_head)
769 ret |= terminate_and_release_chain (m_stores_head);
770 gcc_assert (m_stores.elements () == 0);
771 gcc_assert (m_stores_head == NULL);
3d3e04ac 772
773 return ret;
774}
775
776/* Terminate all chains that are affected by the assignment to DEST, appearing
777 in statement STMT and ultimately points to the object BASE. Return true if
778 at least one aliasing chain was terminated. BASE and DEST are allowed to
779 be NULL_TREE. In that case the aliasing checks are performed on the whole
780 statement rather than a particular operand in it. VAR_OFFSET_P signifies
781 whether STMT represents a store to BASE offset by a variable amount.
782 If that is the case we have to terminate any chain anchored at BASE. */
783
784bool
4de7f8df 785pass_store_merging::terminate_all_aliasing_chains (imm_store_chain_info
f85e7cb7 786 **chain_info,
3d3e04ac 787 bool var_offset_p,
788 gimple *stmt)
789{
790 bool ret = false;
791
792 /* If the statement doesn't touch memory it can't alias. */
793 if (!gimple_vuse (stmt))
794 return false;
795
3d3e04ac 796 /* Check if the assignment destination (BASE) is part of a store chain.
797 This is to catch non-constant stores to destinations that may be part
798 of a chain. */
f85e7cb7 799 if (chain_info)
3d3e04ac 800 {
f85e7cb7 801 /* We have a chain at BASE and we're writing to [BASE + <variable>].
802 This can interfere with any of the stores so terminate
803 the chain. */
804 if (var_offset_p)
3d3e04ac 805 {
f85e7cb7 806 terminate_and_release_chain (*chain_info);
807 ret = true;
808 }
809 /* Otherwise go through every store in the chain to see if it
810 aliases with any of them. */
811 else
812 {
813 struct store_immediate_info *info;
814 unsigned int i;
815 FOR_EACH_VEC_ELT ((*chain_info)->m_store_info, i, info)
3d3e04ac 816 {
4de7f8df 817 if (ref_maybe_used_by_stmt_p (stmt,
818 gimple_assign_lhs (info->stmt))
819 || stmt_may_clobber_ref_p (stmt,
820 gimple_assign_lhs (info->stmt)))
3d3e04ac 821 {
f85e7cb7 822 if (dump_file && (dump_flags & TDF_DETAILS))
3d3e04ac 823 {
f85e7cb7 824 fprintf (dump_file,
825 "stmt causes chain termination:\n");
1ffa4346 826 print_gimple_stmt (dump_file, stmt, 0);
3d3e04ac 827 }
f85e7cb7 828 terminate_and_release_chain (*chain_info);
829 ret = true;
830 break;
3d3e04ac 831 }
832 }
833 }
834 }
835
3d3e04ac 836 /* Check for aliasing with all other store chains. */
3a3ba7de 837 for (imm_store_chain_info *next = m_stores_head, *cur = next; cur; cur = next)
3d3e04ac 838 {
3a3ba7de 839 next = cur->next;
840
3d3e04ac 841 /* We already checked all the stores in chain_info and terminated the
842 chain if necessary. Skip it here. */
3a3ba7de 843 if (chain_info && (*chain_info) == cur)
3d3e04ac 844 continue;
845
f85e7cb7 846 /* We can't use the base object here as that does not reliably exist.
847 Build a ao_ref from the base object address (if we know the
848 minimum and maximum offset and the maximum size we could improve
849 things here). */
850 ao_ref chain_ref;
3a3ba7de 851 ao_ref_init_from_ptr_and_size (&chain_ref, cur->base_addr, NULL_TREE);
f85e7cb7 852 if (ref_maybe_used_by_stmt_p (stmt, &chain_ref)
853 || stmt_may_clobber_ref_p_1 (stmt, &chain_ref))
3d3e04ac 854 {
3a3ba7de 855 terminate_and_release_chain (cur);
3d3e04ac 856 ret = true;
857 }
858 }
859
860 return ret;
861}
862
863/* Helper function. Terminate the recorded chain storing to base object
864 BASE. Return true if the merging and output was successful. The m_stores
865 entry is removed after the processing in any case. */
866
867bool
f85e7cb7 868pass_store_merging::terminate_and_release_chain (imm_store_chain_info *chain_info)
3d3e04ac 869{
f85e7cb7 870 bool ret = chain_info->terminate_and_process_chain ();
871 m_stores.remove (chain_info->base_addr);
872 delete chain_info;
3d3e04ac 873 return ret;
874}
875
876/* Go through the candidate stores recorded in m_store_info and merge them
877 into merged_store_group objects recorded into m_merged_store_groups
878 representing the widened stores. Return true if coalescing was successful
879 and the number of widened stores is fewer than the original number
880 of stores. */
881
882bool
883imm_store_chain_info::coalesce_immediate_stores ()
884{
885 /* Anything less can't be processed. */
886 if (m_store_info.length () < 2)
887 return false;
888
889 if (dump_file && (dump_flags & TDF_DETAILS))
890 fprintf (dump_file, "Attempting to coalesce %u stores in chain.\n",
891 m_store_info.length ());
892
893 store_immediate_info *info;
894 unsigned int i;
895
896 /* Order the stores by the bitposition they write to. */
897 m_store_info.qsort (sort_by_bitpos);
898
899 info = m_store_info[0];
900 merged_store_group *merged_store = new merged_store_group (info);
901
902 FOR_EACH_VEC_ELT (m_store_info, i, info)
903 {
904 if (dump_file && (dump_flags & TDF_DETAILS))
905 {
906 fprintf (dump_file, "Store %u:\nbitsize:" HOST_WIDE_INT_PRINT_DEC
907 " bitpos:" HOST_WIDE_INT_PRINT_DEC " val:\n",
908 i, info->bitsize, info->bitpos);
1ffa4346 909 print_generic_expr (dump_file, gimple_assign_rhs1 (info->stmt));
3d3e04ac 910 fprintf (dump_file, "\n------------\n");
911 }
912
913 if (i == 0)
914 continue;
915
916 /* |---store 1---|
917 |---store 2---|
918 Overlapping stores. */
919 unsigned HOST_WIDE_INT start = info->bitpos;
920 if (IN_RANGE (start, merged_store->start,
921 merged_store->start + merged_store->width - 1))
922 {
923 merged_store->merge_overlapping (info);
924 continue;
925 }
926
927 /* |---store 1---| <gap> |---store 2---|.
928 Gap between stores. Start a new group. */
929 if (start != merged_store->start + merged_store->width)
930 {
931 /* Try to apply all the stores recorded for the group to determine
932 the bitpattern they write and discard it if that fails.
933 This will also reject single-store groups. */
934 if (!merged_store->apply_stores ())
935 delete merged_store;
936 else
937 m_merged_store_groups.safe_push (merged_store);
938
939 merged_store = new merged_store_group (info);
940
941 continue;
942 }
943
944 /* |---store 1---||---store 2---|
945 This store is consecutive to the previous one.
946 Merge it into the current store group. */
947 merged_store->merge_into (info);
948 }
949
950 /* Record or discard the last store group. */
951 if (!merged_store->apply_stores ())
952 delete merged_store;
953 else
954 m_merged_store_groups.safe_push (merged_store);
955
956 gcc_assert (m_merged_store_groups.length () <= m_store_info.length ());
957 bool success
958 = !m_merged_store_groups.is_empty ()
959 && m_merged_store_groups.length () < m_store_info.length ();
960
961 if (success && dump_file)
962 fprintf (dump_file, "Coalescing successful!\n"
963 "Merged into %u stores\n",
964 m_merged_store_groups.length ());
965
966 return success;
967}
968
969/* Return the type to use for the merged stores described by STMTS.
970 This is needed to get the alias sets right. */
971
972static tree
973get_alias_type_for_stmts (auto_vec<gimple *> &stmts)
974{
975 gimple *stmt;
976 unsigned int i;
977 tree lhs = gimple_assign_lhs (stmts[0]);
978 tree type = reference_alias_ptr_type (lhs);
979
980 FOR_EACH_VEC_ELT (stmts, i, stmt)
981 {
982 if (i == 0)
983 continue;
984
985 lhs = gimple_assign_lhs (stmt);
986 tree type1 = reference_alias_ptr_type (lhs);
987 if (!alias_ptr_types_compatible_p (type, type1))
988 return ptr_type_node;
989 }
990 return type;
991}
992
993/* Return the location_t information we can find among the statements
994 in STMTS. */
995
996static location_t
997get_location_for_stmts (auto_vec<gimple *> &stmts)
998{
999 gimple *stmt;
1000 unsigned int i;
1001
1002 FOR_EACH_VEC_ELT (stmts, i, stmt)
1003 if (gimple_has_location (stmt))
1004 return gimple_location (stmt);
1005
1006 return UNKNOWN_LOCATION;
1007}
1008
1009/* Used to decribe a store resulting from splitting a wide store in smaller
1010 regularly-sized stores in split_group. */
1011
1012struct split_store
1013{
1014 unsigned HOST_WIDE_INT bytepos;
1015 unsigned HOST_WIDE_INT size;
1016 unsigned HOST_WIDE_INT align;
1017 auto_vec<gimple *> orig_stmts;
1018 split_store (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT,
1019 unsigned HOST_WIDE_INT);
1020};
1021
1022/* Simple constructor. */
1023
1024split_store::split_store (unsigned HOST_WIDE_INT bp,
1025 unsigned HOST_WIDE_INT sz,
1026 unsigned HOST_WIDE_INT al)
1027 : bytepos (bp), size (sz), align (al)
1028{
1029 orig_stmts.create (0);
1030}
1031
1032/* Record all statements corresponding to stores in GROUP that write to
1033 the region starting at BITPOS and is of size BITSIZE. Record such
1034 statements in STMTS. The stores in GROUP must be sorted by
1035 bitposition. */
1036
1037static void
1038find_constituent_stmts (struct merged_store_group *group,
1039 auto_vec<gimple *> &stmts,
1040 unsigned HOST_WIDE_INT bitpos,
1041 unsigned HOST_WIDE_INT bitsize)
1042{
1043 struct store_immediate_info *info;
1044 unsigned int i;
1045 unsigned HOST_WIDE_INT end = bitpos + bitsize;
1046 FOR_EACH_VEC_ELT (group->stores, i, info)
1047 {
1048 unsigned HOST_WIDE_INT stmt_start = info->bitpos;
1049 unsigned HOST_WIDE_INT stmt_end = stmt_start + info->bitsize;
1050 if (stmt_end < bitpos)
1051 continue;
1052 /* The stores in GROUP are ordered by bitposition so if we're past
1053 the region for this group return early. */
1054 if (stmt_start > end)
1055 return;
1056
1057 if (IN_RANGE (stmt_start, bitpos, bitpos + bitsize)
1058 || IN_RANGE (stmt_end, bitpos, end)
1059 /* The statement writes a region that completely encloses the region
1060 that this group writes. Unlikely to occur but let's
1061 handle it. */
1062 || IN_RANGE (bitpos, stmt_start, stmt_end))
1063 stmts.safe_push (info->stmt);
1064 }
1065}
1066
1067/* Split a merged store described by GROUP by populating the SPLIT_STORES
1068 vector with split_store structs describing the byte offset (from the base),
1069 the bit size and alignment of each store as well as the original statements
1070 involved in each such split group.
1071 This is to separate the splitting strategy from the statement
1072 building/emission/linking done in output_merged_store.
1073 At the moment just start with the widest possible size and keep emitting
1074 the widest we can until we have emitted all the bytes, halving the size
1075 when appropriate. */
1076
1077static bool
1078split_group (merged_store_group *group,
1079 auto_vec<struct split_store *> &split_stores)
1080{
1081 unsigned HOST_WIDE_INT pos = group->start;
1082 unsigned HOST_WIDE_INT size = group->width;
1083 unsigned HOST_WIDE_INT bytepos = pos / BITS_PER_UNIT;
1084 unsigned HOST_WIDE_INT align = group->align;
1085
1086 /* We don't handle partial bitfields for now. We shouldn't have
1087 reached this far. */
1088 gcc_assert ((size % BITS_PER_UNIT == 0) && (pos % BITS_PER_UNIT == 0));
1089
1090 bool allow_unaligned
1091 = !STRICT_ALIGNMENT && PARAM_VALUE (PARAM_STORE_MERGING_ALLOW_UNALIGNED);
1092
1093 unsigned int try_size = MAX_STORE_BITSIZE;
1094 while (try_size > size
1095 || (!allow_unaligned
1096 && try_size > align))
1097 {
1098 try_size /= 2;
1099 if (try_size < BITS_PER_UNIT)
1100 return false;
1101 }
1102
1103 unsigned HOST_WIDE_INT try_pos = bytepos;
1104 group->stores.qsort (sort_by_bitpos);
1105
1106 while (size > 0)
1107 {
1108 struct split_store *store = new split_store (try_pos, try_size, align);
1109 unsigned HOST_WIDE_INT try_bitpos = try_pos * BITS_PER_UNIT;
1110 find_constituent_stmts (group, store->orig_stmts, try_bitpos, try_size);
1111 split_stores.safe_push (store);
1112
1113 try_pos += try_size / BITS_PER_UNIT;
1114
1115 size -= try_size;
1116 align = try_size;
1117 while (size < try_size)
1118 try_size /= 2;
1119 }
1120 return true;
1121}
1122
1123/* Given a merged store group GROUP output the widened version of it.
1124 The store chain is against the base object BASE.
1125 Try store sizes of at most MAX_STORE_BITSIZE bits wide and don't output
1126 unaligned stores for STRICT_ALIGNMENT targets or if it's too expensive.
1127 Make sure that the number of statements output is less than the number of
1128 original statements. If a better sequence is possible emit it and
1129 return true. */
1130
1131bool
f85e7cb7 1132imm_store_chain_info::output_merged_store (merged_store_group *group)
3d3e04ac 1133{
1134 unsigned HOST_WIDE_INT start_byte_pos = group->start / BITS_PER_UNIT;
1135
1136 unsigned int orig_num_stmts = group->stores.length ();
1137 if (orig_num_stmts < 2)
1138 return false;
1139
1140 auto_vec<struct split_store *> split_stores;
1141 split_stores.create (0);
1142 if (!split_group (group, split_stores))
1143 return false;
1144
1145 gimple_stmt_iterator last_gsi = gsi_for_stmt (group->last_stmt);
1146 gimple_seq seq = NULL;
1147 unsigned int num_stmts = 0;
1148 tree last_vdef, new_vuse;
1149 last_vdef = gimple_vdef (group->last_stmt);
1150 new_vuse = gimple_vuse (group->last_stmt);
1151
1152 gimple *stmt = NULL;
1153 /* The new SSA names created. Keep track of them so that we can free them
1154 if we decide to not use the new sequence. */
1155 auto_vec<tree> new_ssa_names;
1156 split_store *split_store;
1157 unsigned int i;
1158 bool fail = false;
1159
427223f1 1160 tree addr = force_gimple_operand_1 (unshare_expr (base_addr), &seq,
1161 is_gimple_mem_ref_addr, NULL_TREE);
3d3e04ac 1162 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1163 {
1164 unsigned HOST_WIDE_INT try_size = split_store->size;
1165 unsigned HOST_WIDE_INT try_pos = split_store->bytepos;
1166 unsigned HOST_WIDE_INT align = split_store->align;
1167 tree offset_type = get_alias_type_for_stmts (split_store->orig_stmts);
1168 location_t loc = get_location_for_stmts (split_store->orig_stmts);
1169
1170 tree int_type = build_nonstandard_integer_type (try_size, UNSIGNED);
f6443ac9 1171 int_type = build_aligned_type (int_type, align);
427223f1 1172 tree dest = fold_build2 (MEM_REF, int_type, addr,
3d3e04ac 1173 build_int_cst (offset_type, try_pos));
1174
1175 tree src = native_interpret_expr (int_type,
1176 group->val + try_pos - start_byte_pos,
1177 group->buf_size);
1178
1179 stmt = gimple_build_assign (dest, src);
1180 gimple_set_location (stmt, loc);
1181 gimple_set_vuse (stmt, new_vuse);
1182 gimple_seq_add_stmt_without_update (&seq, stmt);
1183
1184 /* We didn't manage to reduce the number of statements. Bail out. */
1185 if (++num_stmts == orig_num_stmts)
1186 {
1187 if (dump_file && (dump_flags & TDF_DETAILS))
1188 {
1189 fprintf (dump_file, "Exceeded original number of stmts (%u)."
1190 " Not profitable to emit new sequence.\n",
1191 orig_num_stmts);
1192 }
1193 unsigned int ssa_count;
1194 tree ssa_name;
1195 /* Don't forget to cleanup the temporary SSA names. */
1196 FOR_EACH_VEC_ELT (new_ssa_names, ssa_count, ssa_name)
1197 release_ssa_name (ssa_name);
1198
1199 fail = true;
1200 break;
1201 }
1202
1203 tree new_vdef;
1204 if (i < split_stores.length () - 1)
1205 {
1206 new_vdef = make_ssa_name (gimple_vop (cfun), stmt);
1207 new_ssa_names.safe_push (new_vdef);
1208 }
1209 else
1210 new_vdef = last_vdef;
1211
1212 gimple_set_vdef (stmt, new_vdef);
1213 SSA_NAME_DEF_STMT (new_vdef) = stmt;
1214 new_vuse = new_vdef;
1215 }
1216
1217 FOR_EACH_VEC_ELT (split_stores, i, split_store)
1218 delete split_store;
1219
1220 if (fail)
1221 return false;
1222
1223 gcc_assert (seq);
1224 if (dump_file)
1225 {
1226 fprintf (dump_file,
1227 "New sequence of %u stmts to replace old one of %u stmts\n",
1228 num_stmts, orig_num_stmts);
1229 if (dump_flags & TDF_DETAILS)
1230 print_gimple_seq (dump_file, seq, 0, TDF_VOPS | TDF_MEMSYMS);
1231 }
1232 gsi_insert_seq_after (&last_gsi, seq, GSI_SAME_STMT);
1233
1234 return true;
1235}
1236
1237/* Process the merged_store_group objects created in the coalescing phase.
1238 The stores are all against the base object BASE.
1239 Try to output the widened stores and delete the original statements if
1240 successful. Return true iff any changes were made. */
1241
1242bool
f85e7cb7 1243imm_store_chain_info::output_merged_stores ()
3d3e04ac 1244{
1245 unsigned int i;
1246 merged_store_group *merged_store;
1247 bool ret = false;
1248 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_store)
1249 {
f85e7cb7 1250 if (output_merged_store (merged_store))
3d3e04ac 1251 {
1252 unsigned int j;
1253 store_immediate_info *store;
1254 FOR_EACH_VEC_ELT (merged_store->stores, j, store)
1255 {
1256 gimple *stmt = store->stmt;
1257 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1258 gsi_remove (&gsi, true);
1259 if (stmt != merged_store->last_stmt)
1260 {
1261 unlink_stmt_vdef (stmt);
1262 release_defs (stmt);
1263 }
1264 }
1265 ret = true;
1266 }
1267 }
1268 if (ret && dump_file)
1269 fprintf (dump_file, "Merging successful!\n");
1270
1271 return ret;
1272}
1273
1274/* Coalesce the store_immediate_info objects recorded against the base object
1275 BASE in the first phase and output them.
1276 Delete the allocated structures.
1277 Return true if any changes were made. */
1278
1279bool
f85e7cb7 1280imm_store_chain_info::terminate_and_process_chain ()
3d3e04ac 1281{
1282 /* Process store chain. */
1283 bool ret = false;
1284 if (m_store_info.length () > 1)
1285 {
1286 ret = coalesce_immediate_stores ();
1287 if (ret)
f85e7cb7 1288 ret = output_merged_stores ();
3d3e04ac 1289 }
1290
1291 /* Delete all the entries we allocated ourselves. */
1292 store_immediate_info *info;
1293 unsigned int i;
1294 FOR_EACH_VEC_ELT (m_store_info, i, info)
1295 delete info;
1296
1297 merged_store_group *merged_info;
1298 FOR_EACH_VEC_ELT (m_merged_store_groups, i, merged_info)
1299 delete merged_info;
1300
1301 return ret;
1302}
1303
1304/* Return true iff LHS is a destination potentially interesting for
1305 store merging. In practice these are the codes that get_inner_reference
1306 can process. */
1307
1308static bool
1309lhs_valid_for_store_merging_p (tree lhs)
1310{
1311 tree_code code = TREE_CODE (lhs);
1312
1313 if (code == ARRAY_REF || code == ARRAY_RANGE_REF || code == MEM_REF
1314 || code == COMPONENT_REF || code == BIT_FIELD_REF)
1315 return true;
1316
1317 return false;
1318}
1319
1320/* Return true if the tree RHS is a constant we want to consider
1321 during store merging. In practice accept all codes that
1322 native_encode_expr accepts. */
1323
1324static bool
1325rhs_valid_for_store_merging_p (tree rhs)
1326{
1327 tree type = TREE_TYPE (rhs);
1328 if (TREE_CODE_CLASS (TREE_CODE (rhs)) != tcc_constant
1329 || !can_native_encode_type_p (type))
1330 return false;
1331
1332 return true;
1333}
1334
1335/* Entry point for the pass. Go over each basic block recording chains of
1336 immediate stores. Upon encountering a terminating statement (as defined
1337 by stmt_terminates_chain_p) process the recorded stores and emit the widened
1338 variants. */
1339
1340unsigned int
1341pass_store_merging::execute (function *fun)
1342{
1343 basic_block bb;
1344 hash_set<gimple *> orig_stmts;
1345
1346 FOR_EACH_BB_FN (bb, fun)
1347 {
1348 gimple_stmt_iterator gsi;
1349 unsigned HOST_WIDE_INT num_statements = 0;
1350 /* Record the original statements so that we can keep track of
1351 statements emitted in this pass and not re-process new
1352 statements. */
1353 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1354 {
1355 if (is_gimple_debug (gsi_stmt (gsi)))
1356 continue;
1357
1358 if (++num_statements > 2)
1359 break;
1360 }
1361
1362 if (num_statements < 2)
1363 continue;
1364
1365 if (dump_file && (dump_flags & TDF_DETAILS))
1366 fprintf (dump_file, "Processing basic block <%d>:\n", bb->index);
1367
1368 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1369 {
1370 gimple *stmt = gsi_stmt (gsi);
1371
3a3ba7de 1372 if (is_gimple_debug (stmt))
1373 continue;
1374
3d3e04ac 1375 if (gimple_has_volatile_ops (stmt))
1376 {
1377 /* Terminate all chains. */
1378 if (dump_file && (dump_flags & TDF_DETAILS))
1379 fprintf (dump_file, "Volatile access terminates "
1380 "all chains\n");
1381 terminate_and_process_all_chains ();
1382 continue;
1383 }
1384
3d3e04ac 1385 if (gimple_assign_single_p (stmt) && gimple_vdef (stmt)
1386 && !stmt_can_throw_internal (stmt)
1387 && lhs_valid_for_store_merging_p (gimple_assign_lhs (stmt)))
1388 {
1389 tree lhs = gimple_assign_lhs (stmt);
1390 tree rhs = gimple_assign_rhs1 (stmt);
1391
1392 HOST_WIDE_INT bitsize, bitpos;
1393 machine_mode mode;
1394 int unsignedp = 0, reversep = 0, volatilep = 0;
1395 tree offset, base_addr;
1396 base_addr
1397 = get_inner_reference (lhs, &bitsize, &bitpos, &offset, &mode,
1398 &unsignedp, &reversep, &volatilep);
1399 /* As a future enhancement we could handle stores with the same
1400 base and offset. */
427223f1 1401 bool invalid = reversep
3d3e04ac 1402 || ((bitsize > MAX_BITSIZE_MODE_ANY_INT)
1403 && (TREE_CODE (rhs) != INTEGER_CST))
427223f1 1404 || !rhs_valid_for_store_merging_p (rhs);
3d3e04ac 1405
f85e7cb7 1406 /* We do not want to rewrite TARGET_MEM_REFs. */
1407 if (TREE_CODE (base_addr) == TARGET_MEM_REF)
1408 invalid = true;
3d3e04ac 1409 /* In some cases get_inner_reference may return a
1410 MEM_REF [ptr + byteoffset]. For the purposes of this pass
1411 canonicalize the base_addr to MEM_REF [ptr] and take
1412 byteoffset into account in the bitpos. This occurs in
1413 PR 23684 and this way we can catch more chains. */
f85e7cb7 1414 else if (TREE_CODE (base_addr) == MEM_REF)
3d3e04ac 1415 {
1416 offset_int bit_off, byte_off = mem_ref_offset (base_addr);
1417 bit_off = byte_off << LOG2_BITS_PER_UNIT;
1418 bit_off += bitpos;
1419 if (!wi::neg_p (bit_off) && wi::fits_shwi_p (bit_off))
f85e7cb7 1420 bitpos = bit_off.to_shwi ();
3d3e04ac 1421 else
1422 invalid = true;
f85e7cb7 1423 base_addr = TREE_OPERAND (base_addr, 0);
3d3e04ac 1424 }
f85e7cb7 1425 /* get_inner_reference returns the base object, get at its
1426 address now. */
1427 else
427223f1 1428 {
1429 if (bitpos < 0)
1430 invalid = true;
1431 base_addr = build_fold_addr_expr (base_addr);
1432 }
1433
1434 if (! invalid
1435 && offset != NULL_TREE)
1436 {
1437 /* If the access is variable offset then a base
1438 decl has to be address-taken to be able to
1439 emit pointer-based stores to it.
1440 ??? We might be able to get away with
1441 re-using the original base up to the first
1442 variable part and then wrapping that inside
1443 a BIT_FIELD_REF. */
1444 tree base = get_base_address (base_addr);
1445 if (! base
1446 || (DECL_P (base)
1447 && ! TREE_ADDRESSABLE (base)))
1448 invalid = true;
1449 else
1450 base_addr = build2 (POINTER_PLUS_EXPR,
1451 TREE_TYPE (base_addr),
1452 base_addr, offset);
1453 }
3d3e04ac 1454
1455 struct imm_store_chain_info **chain_info
1456 = m_stores.get (base_addr);
1457
1458 if (!invalid)
1459 {
1460 store_immediate_info *info;
1461 if (chain_info)
1462 {
1463 info = new store_immediate_info (
f85e7cb7 1464 bitsize, bitpos, stmt,
3d3e04ac 1465 (*chain_info)->m_store_info.length ());
1466 if (dump_file && (dump_flags & TDF_DETAILS))
1467 {
1468 fprintf (dump_file,
1469 "Recording immediate store from stmt:\n");
1ffa4346 1470 print_gimple_stmt (dump_file, stmt, 0);
3d3e04ac 1471 }
1472 (*chain_info)->m_store_info.safe_push (info);
1473 /* If we reach the limit of stores to merge in a chain
1474 terminate and process the chain now. */
1475 if ((*chain_info)->m_store_info.length ()
1476 == (unsigned int)
1477 PARAM_VALUE (PARAM_MAX_STORES_TO_MERGE))
1478 {
1479 if (dump_file && (dump_flags & TDF_DETAILS))
1480 fprintf (dump_file,
1481 "Reached maximum number of statements"
1482 " to merge:\n");
f85e7cb7 1483 terminate_and_release_chain (*chain_info);
3d3e04ac 1484 }
1485 continue;
1486 }
1487
1488 /* Store aliases any existing chain? */
4de7f8df 1489 terminate_all_aliasing_chains (chain_info, false, stmt);
3d3e04ac 1490 /* Start a new chain. */
1491 struct imm_store_chain_info *new_chain
3a3ba7de 1492 = new imm_store_chain_info (m_stores_head, base_addr);
f85e7cb7 1493 info = new store_immediate_info (bitsize, bitpos,
3d3e04ac 1494 stmt, 0);
1495 new_chain->m_store_info.safe_push (info);
1496 m_stores.put (base_addr, new_chain);
1497 if (dump_file && (dump_flags & TDF_DETAILS))
1498 {
1499 fprintf (dump_file,
1500 "Starting new chain with statement:\n");
1ffa4346 1501 print_gimple_stmt (dump_file, stmt, 0);
3d3e04ac 1502 fprintf (dump_file, "The base object is:\n");
1ffa4346 1503 print_generic_expr (dump_file, base_addr);
3d3e04ac 1504 fprintf (dump_file, "\n");
1505 }
1506 }
1507 else
4de7f8df 1508 terminate_all_aliasing_chains (chain_info,
3d3e04ac 1509 offset != NULL_TREE, stmt);
1510
1511 continue;
1512 }
1513
4de7f8df 1514 terminate_all_aliasing_chains (NULL, false, stmt);
3d3e04ac 1515 }
1516 terminate_and_process_all_chains ();
1517 }
1518 return 0;
1519}
1520
1521} // anon namespace
1522
1523/* Construct and return a store merging pass object. */
1524
1525gimple_opt_pass *
1526make_pass_store_merging (gcc::context *ctxt)
1527{
1528 return new pass_store_merging (ctxt);
1529}
3d9a2fb3 1530
1531#if CHECKING_P
1532
1533namespace selftest {
1534
1535/* Selftests for store merging helpers. */
1536
1537/* Assert that all elements of the byte arrays X and Y, both of length N
1538 are equal. */
1539
1540static void
1541verify_array_eq (unsigned char *x, unsigned char *y, unsigned int n)
1542{
1543 for (unsigned int i = 0; i < n; i++)
1544 {
1545 if (x[i] != y[i])
1546 {
1547 fprintf (stderr, "Arrays do not match. X:\n");
1548 dump_char_array (stderr, x, n);
1549 fprintf (stderr, "Y:\n");
1550 dump_char_array (stderr, y, n);
1551 }
1552 ASSERT_EQ (x[i], y[i]);
1553 }
1554}
1555
1556/* Test shift_bytes_in_array and that it carries bits across between
1557 bytes correctly. */
1558
1559static void
1560verify_shift_bytes_in_array (void)
1561{
1562 /* byte 1 | byte 0
1563 00011111 | 11100000. */
1564 unsigned char orig[2] = { 0xe0, 0x1f };
1565 unsigned char in[2];
1566 memcpy (in, orig, sizeof orig);
1567
1568 unsigned char expected[2] = { 0x80, 0x7f };
1569 shift_bytes_in_array (in, sizeof (in), 2);
1570 verify_array_eq (in, expected, sizeof (in));
1571
1572 memcpy (in, orig, sizeof orig);
1573 memcpy (expected, orig, sizeof orig);
1574 /* Check that shifting by zero doesn't change anything. */
1575 shift_bytes_in_array (in, sizeof (in), 0);
1576 verify_array_eq (in, expected, sizeof (in));
1577
1578}
1579
1580/* Test shift_bytes_in_array_right and that it carries bits across between
1581 bytes correctly. */
1582
1583static void
1584verify_shift_bytes_in_array_right (void)
1585{
1586 /* byte 1 | byte 0
1587 00011111 | 11100000. */
1588 unsigned char orig[2] = { 0x1f, 0xe0};
1589 unsigned char in[2];
1590 memcpy (in, orig, sizeof orig);
1591 unsigned char expected[2] = { 0x07, 0xf8};
1592 shift_bytes_in_array_right (in, sizeof (in), 2);
1593 verify_array_eq (in, expected, sizeof (in));
1594
1595 memcpy (in, orig, sizeof orig);
1596 memcpy (expected, orig, sizeof orig);
1597 /* Check that shifting by zero doesn't change anything. */
1598 shift_bytes_in_array_right (in, sizeof (in), 0);
1599 verify_array_eq (in, expected, sizeof (in));
1600}
1601
1602/* Test clear_bit_region that it clears exactly the bits asked and
1603 nothing more. */
1604
1605static void
1606verify_clear_bit_region (void)
1607{
1608 /* Start with all bits set and test clearing various patterns in them. */
1609 unsigned char orig[3] = { 0xff, 0xff, 0xff};
1610 unsigned char in[3];
1611 unsigned char expected[3];
1612 memcpy (in, orig, sizeof in);
1613
1614 /* Check zeroing out all the bits. */
1615 clear_bit_region (in, 0, 3 * BITS_PER_UNIT);
1616 expected[0] = expected[1] = expected[2] = 0;
1617 verify_array_eq (in, expected, sizeof in);
1618
1619 memcpy (in, orig, sizeof in);
1620 /* Leave the first and last bits intact. */
1621 clear_bit_region (in, 1, 3 * BITS_PER_UNIT - 2);
1622 expected[0] = 0x1;
1623 expected[1] = 0;
1624 expected[2] = 0x80;
1625 verify_array_eq (in, expected, sizeof in);
1626}
1627
1628/* Test verify_clear_bit_region_be that it clears exactly the bits asked and
1629 nothing more. */
1630
1631static void
1632verify_clear_bit_region_be (void)
1633{
1634 /* Start with all bits set and test clearing various patterns in them. */
1635 unsigned char orig[3] = { 0xff, 0xff, 0xff};
1636 unsigned char in[3];
1637 unsigned char expected[3];
1638 memcpy (in, orig, sizeof in);
1639
1640 /* Check zeroing out all the bits. */
1641 clear_bit_region_be (in, BITS_PER_UNIT - 1, 3 * BITS_PER_UNIT);
1642 expected[0] = expected[1] = expected[2] = 0;
1643 verify_array_eq (in, expected, sizeof in);
1644
1645 memcpy (in, orig, sizeof in);
1646 /* Leave the first and last bits intact. */
1647 clear_bit_region_be (in, BITS_PER_UNIT - 2, 3 * BITS_PER_UNIT - 2);
1648 expected[0] = 0x80;
1649 expected[1] = 0;
1650 expected[2] = 0x1;
1651 verify_array_eq (in, expected, sizeof in);
1652}
1653
1654
1655/* Run all of the selftests within this file. */
1656
1657void
1658store_merging_c_tests (void)
1659{
1660 verify_shift_bytes_in_array ();
1661 verify_shift_bytes_in_array_right ();
1662 verify_clear_bit_region ();
1663 verify_clear_bit_region_be ();
1664}
1665
1666} // namespace selftest
1667#endif /* CHECKING_P. */