PR sanitizer/59009
[official-gcc.git] / gcc / trans-mem.c
blobe821c99c9754ca2d546985485fa3cdb358f96533
1 /* Passes for transactional memory support.
2 Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hash-table.h"
24 #include "tree.h"
25 #include "gimplify.h"
26 #include "gimple-ssa.h"
27 #include "cgraph.h"
28 #include "tree-cfg.h"
29 #include "tree-ssanames.h"
30 #include "tree-into-ssa.h"
31 #include "tree-pass.h"
32 #include "tree-inline.h"
33 #include "diagnostic-core.h"
34 #include "demangle.h"
35 #include "output.h"
36 #include "trans-mem.h"
37 #include "params.h"
38 #include "target.h"
39 #include "langhooks.h"
40 #include "gimple-pretty-print.h"
41 #include "cfgloop.h"
42 #include "tree-ssa-address.h"
45 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
46 #define PROB_VERY_LIKELY (PROB_ALWAYS - PROB_VERY_UNLIKELY)
47 #define PROB_UNLIKELY (REG_BR_PROB_BASE / 5 - 1)
48 #define PROB_LIKELY (PROB_ALWAYS - PROB_VERY_LIKELY)
49 #define PROB_ALWAYS (REG_BR_PROB_BASE)
51 #define A_RUNINSTRUMENTEDCODE 0x0001
52 #define A_RUNUNINSTRUMENTEDCODE 0x0002
53 #define A_SAVELIVEVARIABLES 0x0004
54 #define A_RESTORELIVEVARIABLES 0x0008
55 #define A_ABORTTRANSACTION 0x0010
57 #define AR_USERABORT 0x0001
58 #define AR_USERRETRY 0x0002
59 #define AR_TMCONFLICT 0x0004
60 #define AR_EXCEPTIONBLOCKABORT 0x0008
61 #define AR_OUTERABORT 0x0010
63 #define MODE_SERIALIRREVOCABLE 0x0000
66 /* The representation of a transaction changes several times during the
67 lowering process. In the beginning, in the front-end we have the
68 GENERIC tree TRANSACTION_EXPR. For example,
70 __transaction {
71 local++;
72 if (++global == 10)
73 __tm_abort;
76 During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
77 trivially replaced with a GIMPLE_TRANSACTION node.
79 During pass_lower_tm, we examine the body of transactions looking
80 for aborts. Transactions that do not contain an abort may be
81 merged into an outer transaction. We also add a TRY-FINALLY node
82 to arrange for the transaction to be committed on any exit.
84 [??? Think about how this arrangement affects throw-with-commit
85 and throw-with-abort operations. In this case we want the TRY to
86 handle gotos, but not to catch any exceptions because the transaction
87 will already be closed.]
89 GIMPLE_TRANSACTION [label=NULL] {
90 try {
91 local = local + 1;
92 t0 = global;
93 t1 = t0 + 1;
94 global = t1;
95 if (t1 == 10)
96 __builtin___tm_abort ();
97 } finally {
98 __builtin___tm_commit ();
102 During pass_lower_eh, we create EH regions for the transactions,
103 intermixed with the regular EH stuff. This gives us a nice persistent
104 mapping (all the way through rtl) from transactional memory operation
105 back to the transaction, which allows us to get the abnormal edges
106 correct to model transaction aborts and restarts:
108 GIMPLE_TRANSACTION [label=over]
109 local = local + 1;
110 t0 = global;
111 t1 = t0 + 1;
112 global = t1;
113 if (t1 == 10)
114 __builtin___tm_abort ();
115 __builtin___tm_commit ();
116 over:
118 This is the end of all_lowering_passes, and so is what is present
119 during the IPA passes, and through all of the optimization passes.
121 During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
122 functions and mark functions for cloning.
124 At the end of gimple optimization, before exiting SSA form,
125 pass_tm_edges replaces statements that perform transactional
126 memory operations with the appropriate TM builtins, and swap
127 out function calls with their transactional clones. At this
128 point we introduce the abnormal transaction restart edges and
129 complete lowering of the GIMPLE_TRANSACTION node.
131 x = __builtin___tm_start (MAY_ABORT);
132 eh_label:
133 if (x & abort_transaction)
134 goto over;
135 local = local + 1;
136 t0 = __builtin___tm_load (global);
137 t1 = t0 + 1;
138 __builtin___tm_store (&global, t1);
139 if (t1 == 10)
140 __builtin___tm_abort ();
141 __builtin___tm_commit ();
142 over:
145 static void *expand_regions (struct tm_region *,
146 void *(*callback)(struct tm_region *, void *),
147 void *, bool);
150 /* Return the attributes we want to examine for X, or NULL if it's not
151 something we examine. We look at function types, but allow pointers
152 to function types and function decls and peek through. */
154 static tree
155 get_attrs_for (const_tree x)
157 switch (TREE_CODE (x))
159 case FUNCTION_DECL:
160 return TYPE_ATTRIBUTES (TREE_TYPE (x));
161 break;
163 default:
164 if (TYPE_P (x))
165 return NULL;
166 x = TREE_TYPE (x);
167 if (TREE_CODE (x) != POINTER_TYPE)
168 return NULL;
169 /* FALLTHRU */
171 case POINTER_TYPE:
172 x = TREE_TYPE (x);
173 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
174 return NULL;
175 /* FALLTHRU */
177 case FUNCTION_TYPE:
178 case METHOD_TYPE:
179 return TYPE_ATTRIBUTES (x);
183 /* Return true if X has been marked TM_PURE. */
185 bool
186 is_tm_pure (const_tree x)
188 unsigned flags;
190 switch (TREE_CODE (x))
192 case FUNCTION_DECL:
193 case FUNCTION_TYPE:
194 case METHOD_TYPE:
195 break;
197 default:
198 if (TYPE_P (x))
199 return false;
200 x = TREE_TYPE (x);
201 if (TREE_CODE (x) != POINTER_TYPE)
202 return false;
203 /* FALLTHRU */
205 case POINTER_TYPE:
206 x = TREE_TYPE (x);
207 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
208 return false;
209 break;
212 flags = flags_from_decl_or_type (x);
213 return (flags & ECF_TM_PURE) != 0;
216 /* Return true if X has been marked TM_IRREVOCABLE. */
218 static bool
219 is_tm_irrevocable (tree x)
221 tree attrs = get_attrs_for (x);
223 if (attrs && lookup_attribute ("transaction_unsafe", attrs))
224 return true;
226 /* A call to the irrevocable builtin is by definition,
227 irrevocable. */
228 if (TREE_CODE (x) == ADDR_EXPR)
229 x = TREE_OPERAND (x, 0);
230 if (TREE_CODE (x) == FUNCTION_DECL
231 && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
232 && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
233 return true;
235 return false;
238 /* Return true if X has been marked TM_SAFE. */
240 bool
241 is_tm_safe (const_tree x)
243 if (flag_tm)
245 tree attrs = get_attrs_for (x);
246 if (attrs)
248 if (lookup_attribute ("transaction_safe", attrs))
249 return true;
250 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
251 return true;
254 return false;
257 /* Return true if CALL is const, or tm_pure. */
259 static bool
260 is_tm_pure_call (gimple call)
262 tree fn = gimple_call_fn (call);
264 if (TREE_CODE (fn) == ADDR_EXPR)
266 fn = TREE_OPERAND (fn, 0);
267 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
269 else
270 fn = TREE_TYPE (fn);
272 return is_tm_pure (fn);
275 /* Return true if X has been marked TM_CALLABLE. */
277 static bool
278 is_tm_callable (tree x)
280 tree attrs = get_attrs_for (x);
281 if (attrs)
283 if (lookup_attribute ("transaction_callable", attrs))
284 return true;
285 if (lookup_attribute ("transaction_safe", attrs))
286 return true;
287 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
288 return true;
290 return false;
293 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER. */
295 bool
296 is_tm_may_cancel_outer (tree x)
298 tree attrs = get_attrs_for (x);
299 if (attrs)
300 return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
301 return false;
304 /* Return true for built in functions that "end" a transaction. */
306 bool
307 is_tm_ending_fndecl (tree fndecl)
309 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
310 switch (DECL_FUNCTION_CODE (fndecl))
312 case BUILT_IN_TM_COMMIT:
313 case BUILT_IN_TM_COMMIT_EH:
314 case BUILT_IN_TM_ABORT:
315 case BUILT_IN_TM_IRREVOCABLE:
316 return true;
317 default:
318 break;
321 return false;
324 /* Return true if STMT is a TM load. */
326 static bool
327 is_tm_load (gimple stmt)
329 tree fndecl;
331 if (gimple_code (stmt) != GIMPLE_CALL)
332 return false;
334 fndecl = gimple_call_fndecl (stmt);
335 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
336 && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
339 /* Same as above, but for simple TM loads, that is, not the
340 after-write, after-read, etc optimized variants. */
342 static bool
343 is_tm_simple_load (gimple stmt)
345 tree fndecl;
347 if (gimple_code (stmt) != GIMPLE_CALL)
348 return false;
350 fndecl = gimple_call_fndecl (stmt);
351 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
353 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
354 return (fcode == BUILT_IN_TM_LOAD_1
355 || fcode == BUILT_IN_TM_LOAD_2
356 || fcode == BUILT_IN_TM_LOAD_4
357 || fcode == BUILT_IN_TM_LOAD_8
358 || fcode == BUILT_IN_TM_LOAD_FLOAT
359 || fcode == BUILT_IN_TM_LOAD_DOUBLE
360 || fcode == BUILT_IN_TM_LOAD_LDOUBLE
361 || fcode == BUILT_IN_TM_LOAD_M64
362 || fcode == BUILT_IN_TM_LOAD_M128
363 || fcode == BUILT_IN_TM_LOAD_M256);
365 return false;
368 /* Return true if STMT is a TM store. */
370 static bool
371 is_tm_store (gimple stmt)
373 tree fndecl;
375 if (gimple_code (stmt) != GIMPLE_CALL)
376 return false;
378 fndecl = gimple_call_fndecl (stmt);
379 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
380 && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
383 /* Same as above, but for simple TM stores, that is, not the
384 after-write, after-read, etc optimized variants. */
386 static bool
387 is_tm_simple_store (gimple stmt)
389 tree fndecl;
391 if (gimple_code (stmt) != GIMPLE_CALL)
392 return false;
394 fndecl = gimple_call_fndecl (stmt);
395 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
397 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
398 return (fcode == BUILT_IN_TM_STORE_1
399 || fcode == BUILT_IN_TM_STORE_2
400 || fcode == BUILT_IN_TM_STORE_4
401 || fcode == BUILT_IN_TM_STORE_8
402 || fcode == BUILT_IN_TM_STORE_FLOAT
403 || fcode == BUILT_IN_TM_STORE_DOUBLE
404 || fcode == BUILT_IN_TM_STORE_LDOUBLE
405 || fcode == BUILT_IN_TM_STORE_M64
406 || fcode == BUILT_IN_TM_STORE_M128
407 || fcode == BUILT_IN_TM_STORE_M256);
409 return false;
412 /* Return true if FNDECL is BUILT_IN_TM_ABORT. */
414 static bool
415 is_tm_abort (tree fndecl)
417 return (fndecl
418 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
419 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
422 /* Build a GENERIC tree for a user abort. This is called by front ends
423 while transforming the __tm_abort statement. */
425 tree
426 build_tm_abort_call (location_t loc, bool is_outer)
428 return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
429 build_int_cst (integer_type_node,
430 AR_USERABORT
431 | (is_outer ? AR_OUTERABORT : 0)));
434 /* Common gateing function for several of the TM passes. */
436 static bool
437 gate_tm (void)
439 return flag_tm;
442 /* Map for aribtrary function replacement under TM, as created
443 by the tm_wrap attribute. */
445 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
446 htab_t tm_wrap_map;
448 void
449 record_tm_replacement (tree from, tree to)
451 struct tree_map **slot, *h;
453 /* Do not inline wrapper functions that will get replaced in the TM
454 pass.
456 Suppose you have foo() that will get replaced into tmfoo(). Make
457 sure the inliner doesn't try to outsmart us and inline foo()
458 before we get a chance to do the TM replacement. */
459 DECL_UNINLINABLE (from) = 1;
461 if (tm_wrap_map == NULL)
462 tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
464 h = ggc_alloc_tree_map ();
465 h->hash = htab_hash_pointer (from);
466 h->base.from = from;
467 h->to = to;
469 slot = (struct tree_map **)
470 htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
471 *slot = h;
474 /* Return a TM-aware replacement function for DECL. */
476 static tree
477 find_tm_replacement_function (tree fndecl)
479 if (tm_wrap_map)
481 struct tree_map *h, in;
483 in.base.from = fndecl;
484 in.hash = htab_hash_pointer (fndecl);
485 h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
486 if (h)
487 return h->to;
490 /* ??? We may well want TM versions of most of the common <string.h>
491 functions. For now, we've already these two defined. */
492 /* Adjust expand_call_tm() attributes as necessary for the cases
493 handled here: */
494 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
495 switch (DECL_FUNCTION_CODE (fndecl))
497 case BUILT_IN_MEMCPY:
498 return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
499 case BUILT_IN_MEMMOVE:
500 return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
501 case BUILT_IN_MEMSET:
502 return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
503 default:
504 return NULL;
507 return NULL;
510 /* When appropriate, record TM replacement for memory allocation functions.
512 FROM is the FNDECL to wrap. */
513 void
514 tm_malloc_replacement (tree from)
516 const char *str;
517 tree to;
519 if (TREE_CODE (from) != FUNCTION_DECL)
520 return;
522 /* If we have a previous replacement, the user must be explicitly
523 wrapping malloc/calloc/free. They better know what they're
524 doing... */
525 if (find_tm_replacement_function (from))
526 return;
528 str = IDENTIFIER_POINTER (DECL_NAME (from));
530 if (!strcmp (str, "malloc"))
531 to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
532 else if (!strcmp (str, "calloc"))
533 to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
534 else if (!strcmp (str, "free"))
535 to = builtin_decl_explicit (BUILT_IN_TM_FREE);
536 else
537 return;
539 TREE_NOTHROW (to) = 0;
541 record_tm_replacement (from, to);
544 /* Diagnostics for tm_safe functions/regions. Called by the front end
545 once we've lowered the function to high-gimple. */
547 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
548 Process exactly one statement. WI->INFO is set to non-null when in
549 the context of a tm_safe function, and null for a __transaction block. */
551 #define DIAG_TM_OUTER 1
552 #define DIAG_TM_SAFE 2
553 #define DIAG_TM_RELAXED 4
555 struct diagnose_tm
557 unsigned int summary_flags : 8;
558 unsigned int block_flags : 8;
559 unsigned int func_flags : 8;
560 unsigned int saw_volatile : 1;
561 gimple stmt;
564 /* Return true if T is a volatile variable of some kind. */
566 static bool
567 volatile_var_p (tree t)
569 return (SSA_VAR_P (t)
570 && TREE_THIS_VOLATILE (TREE_TYPE (t)));
573 /* Tree callback function for diagnose_tm pass. */
575 static tree
576 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
577 void *data)
579 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
580 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
582 if (volatile_var_p (*tp)
583 && d->block_flags & DIAG_TM_SAFE
584 && !d->saw_volatile)
586 d->saw_volatile = 1;
587 error_at (gimple_location (d->stmt),
588 "invalid volatile use of %qD inside transaction",
589 *tp);
592 return NULL_TREE;
595 static inline bool
596 is_tm_safe_or_pure (const_tree x)
598 return is_tm_safe (x) || is_tm_pure (x);
601 static tree
602 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
603 struct walk_stmt_info *wi)
605 gimple stmt = gsi_stmt (*gsi);
606 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
608 /* Save stmt for use in leaf analysis. */
609 d->stmt = stmt;
611 switch (gimple_code (stmt))
613 case GIMPLE_CALL:
615 tree fn = gimple_call_fn (stmt);
617 if ((d->summary_flags & DIAG_TM_OUTER) == 0
618 && is_tm_may_cancel_outer (fn))
619 error_at (gimple_location (stmt),
620 "%<transaction_may_cancel_outer%> function call not within"
621 " outer transaction or %<transaction_may_cancel_outer%>");
623 if (d->summary_flags & DIAG_TM_SAFE)
625 bool is_safe, direct_call_p;
626 tree replacement;
628 if (TREE_CODE (fn) == ADDR_EXPR
629 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
631 direct_call_p = true;
632 replacement = TREE_OPERAND (fn, 0);
633 replacement = find_tm_replacement_function (replacement);
634 if (replacement)
635 fn = replacement;
637 else
639 direct_call_p = false;
640 replacement = NULL_TREE;
643 if (is_tm_safe_or_pure (fn))
644 is_safe = true;
645 else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
647 /* A function explicitly marked transaction_callable as
648 opposed to transaction_safe is being defined to be
649 unsafe as part of its ABI, regardless of its contents. */
650 is_safe = false;
652 else if (direct_call_p)
654 if (flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
655 is_safe = true;
656 else if (replacement)
658 /* ??? At present we've been considering replacements
659 merely transaction_callable, and therefore might
660 enter irrevocable. The tm_wrap attribute has not
661 yet made it into the new language spec. */
662 is_safe = false;
664 else
666 /* ??? Diagnostics for unmarked direct calls moved into
667 the IPA pass. Section 3.2 of the spec details how
668 functions not marked should be considered "implicitly
669 safe" based on having examined the function body. */
670 is_safe = true;
673 else
675 /* An unmarked indirect call. Consider it unsafe even
676 though optimization may yet figure out how to inline. */
677 is_safe = false;
680 if (!is_safe)
682 if (TREE_CODE (fn) == ADDR_EXPR)
683 fn = TREE_OPERAND (fn, 0);
684 if (d->block_flags & DIAG_TM_SAFE)
686 if (direct_call_p)
687 error_at (gimple_location (stmt),
688 "unsafe function call %qD within "
689 "atomic transaction", fn);
690 else
692 if (!DECL_P (fn) || DECL_NAME (fn))
693 error_at (gimple_location (stmt),
694 "unsafe function call %qE within "
695 "atomic transaction", fn);
696 else
697 error_at (gimple_location (stmt),
698 "unsafe indirect function call within "
699 "atomic transaction");
702 else
704 if (direct_call_p)
705 error_at (gimple_location (stmt),
706 "unsafe function call %qD within "
707 "%<transaction_safe%> function", fn);
708 else
710 if (!DECL_P (fn) || DECL_NAME (fn))
711 error_at (gimple_location (stmt),
712 "unsafe function call %qE within "
713 "%<transaction_safe%> function", fn);
714 else
715 error_at (gimple_location (stmt),
716 "unsafe indirect function call within "
717 "%<transaction_safe%> function");
723 break;
725 case GIMPLE_ASM:
726 /* ??? We ought to come up with a way to add attributes to
727 asm statements, and then add "transaction_safe" to it.
728 Either that or get the language spec to resurrect __tm_waiver. */
729 if (d->block_flags & DIAG_TM_SAFE)
730 error_at (gimple_location (stmt),
731 "asm not allowed in atomic transaction");
732 else if (d->func_flags & DIAG_TM_SAFE)
733 error_at (gimple_location (stmt),
734 "asm not allowed in %<transaction_safe%> function");
735 break;
737 case GIMPLE_TRANSACTION:
739 unsigned char inner_flags = DIAG_TM_SAFE;
741 if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
743 if (d->block_flags & DIAG_TM_SAFE)
744 error_at (gimple_location (stmt),
745 "relaxed transaction in atomic transaction");
746 else if (d->func_flags & DIAG_TM_SAFE)
747 error_at (gimple_location (stmt),
748 "relaxed transaction in %<transaction_safe%> function");
749 inner_flags = DIAG_TM_RELAXED;
751 else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
753 if (d->block_flags)
754 error_at (gimple_location (stmt),
755 "outer transaction in transaction");
756 else if (d->func_flags & DIAG_TM_OUTER)
757 error_at (gimple_location (stmt),
758 "outer transaction in "
759 "%<transaction_may_cancel_outer%> function");
760 else if (d->func_flags & DIAG_TM_SAFE)
761 error_at (gimple_location (stmt),
762 "outer transaction in %<transaction_safe%> function");
763 inner_flags |= DIAG_TM_OUTER;
766 *handled_ops_p = true;
767 if (gimple_transaction_body (stmt))
769 struct walk_stmt_info wi_inner;
770 struct diagnose_tm d_inner;
772 memset (&d_inner, 0, sizeof (d_inner));
773 d_inner.func_flags = d->func_flags;
774 d_inner.block_flags = d->block_flags | inner_flags;
775 d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
777 memset (&wi_inner, 0, sizeof (wi_inner));
778 wi_inner.info = &d_inner;
780 walk_gimple_seq (gimple_transaction_body (stmt),
781 diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
784 break;
786 default:
787 break;
790 return NULL_TREE;
793 static unsigned int
794 diagnose_tm_blocks (void)
796 struct walk_stmt_info wi;
797 struct diagnose_tm d;
799 memset (&d, 0, sizeof (d));
800 if (is_tm_may_cancel_outer (current_function_decl))
801 d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
802 else if (is_tm_safe (current_function_decl))
803 d.func_flags = DIAG_TM_SAFE;
804 d.summary_flags = d.func_flags;
806 memset (&wi, 0, sizeof (wi));
807 wi.info = &d;
809 walk_gimple_seq (gimple_body (current_function_decl),
810 diagnose_tm_1, diagnose_tm_1_op, &wi);
812 return 0;
815 namespace {
817 const pass_data pass_data_diagnose_tm_blocks =
819 GIMPLE_PASS, /* type */
820 "*diagnose_tm_blocks", /* name */
821 OPTGROUP_NONE, /* optinfo_flags */
822 true, /* has_gate */
823 true, /* has_execute */
824 TV_TRANS_MEM, /* tv_id */
825 PROP_gimple_any, /* properties_required */
826 0, /* properties_provided */
827 0, /* properties_destroyed */
828 0, /* todo_flags_start */
829 0, /* todo_flags_finish */
832 class pass_diagnose_tm_blocks : public gimple_opt_pass
834 public:
835 pass_diagnose_tm_blocks (gcc::context *ctxt)
836 : gimple_opt_pass (pass_data_diagnose_tm_blocks, ctxt)
839 /* opt_pass methods: */
840 bool gate () { return gate_tm (); }
841 unsigned int execute () { return diagnose_tm_blocks (); }
843 }; // class pass_diagnose_tm_blocks
845 } // anon namespace
847 gimple_opt_pass *
848 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
850 return new pass_diagnose_tm_blocks (ctxt);
853 /* Instead of instrumenting thread private memory, we save the
854 addresses in a log which we later use to save/restore the addresses
855 upon transaction start/restart.
857 The log is keyed by address, where each element contains individual
858 statements among different code paths that perform the store.
860 This log is later used to generate either plain save/restore of the
861 addresses upon transaction start/restart, or calls to the ITM_L*
862 logging functions.
864 So for something like:
866 struct large { int x[1000]; };
867 struct large lala = { 0 };
868 __transaction {
869 lala.x[i] = 123;
873 We can either save/restore:
875 lala = { 0 };
876 trxn = _ITM_startTransaction ();
877 if (trxn & a_saveLiveVariables)
878 tmp_lala1 = lala.x[i];
879 else if (a & a_restoreLiveVariables)
880 lala.x[i] = tmp_lala1;
882 or use the logging functions:
884 lala = { 0 };
885 trxn = _ITM_startTransaction ();
886 _ITM_LU4 (&lala.x[i]);
888 Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
889 far up the dominator tree to shadow all of the writes to a given
890 location (thus reducing the total number of logging calls), but not
891 so high as to be called on a path that does not perform a
892 write. */
894 /* One individual log entry. We may have multiple statements for the
895 same location if neither dominate each other (on different
896 execution paths). */
897 typedef struct tm_log_entry
899 /* Address to save. */
900 tree addr;
901 /* Entry block for the transaction this address occurs in. */
902 basic_block entry_block;
903 /* Dominating statements the store occurs in. */
904 gimple_vec stmts;
905 /* Initially, while we are building the log, we place a nonzero
906 value here to mean that this address *will* be saved with a
907 save/restore sequence. Later, when generating the save sequence
908 we place the SSA temp generated here. */
909 tree save_var;
910 } *tm_log_entry_t;
913 /* Log entry hashtable helpers. */
915 struct log_entry_hasher
917 typedef tm_log_entry value_type;
918 typedef tm_log_entry compare_type;
919 static inline hashval_t hash (const value_type *);
920 static inline bool equal (const value_type *, const compare_type *);
921 static inline void remove (value_type *);
924 /* Htab support. Return hash value for a `tm_log_entry'. */
925 inline hashval_t
926 log_entry_hasher::hash (const value_type *log)
928 return iterative_hash_expr (log->addr, 0);
931 /* Htab support. Return true if two log entries are the same. */
932 inline bool
933 log_entry_hasher::equal (const value_type *log1, const compare_type *log2)
935 /* FIXME:
937 rth: I suggest that we get rid of the component refs etc.
938 I.e. resolve the reference to base + offset.
940 We may need to actually finish a merge with mainline for this,
941 since we'd like to be presented with Richi's MEM_REF_EXPRs more
942 often than not. But in the meantime your tm_log_entry could save
943 the results of get_inner_reference.
945 See: g++.dg/tm/pr46653.C
948 /* Special case plain equality because operand_equal_p() below will
949 return FALSE if the addresses are equal but they have
950 side-effects (e.g. a volatile address). */
951 if (log1->addr == log2->addr)
952 return true;
954 return operand_equal_p (log1->addr, log2->addr, 0);
957 /* Htab support. Free one tm_log_entry. */
958 inline void
959 log_entry_hasher::remove (value_type *lp)
961 lp->stmts.release ();
962 free (lp);
966 /* The actual log. */
967 static hash_table <log_entry_hasher> tm_log;
969 /* Addresses to log with a save/restore sequence. These should be in
970 dominator order. */
971 static vec<tree> tm_log_save_addresses;
973 enum thread_memory_type
975 mem_non_local = 0,
976 mem_thread_local,
977 mem_transaction_local,
978 mem_max
981 typedef struct tm_new_mem_map
983 /* SSA_NAME being dereferenced. */
984 tree val;
985 enum thread_memory_type local_new_memory;
986 } tm_new_mem_map_t;
988 /* Hashtable helpers. */
990 struct tm_mem_map_hasher : typed_free_remove <tm_new_mem_map_t>
992 typedef tm_new_mem_map_t value_type;
993 typedef tm_new_mem_map_t compare_type;
994 static inline hashval_t hash (const value_type *);
995 static inline bool equal (const value_type *, const compare_type *);
998 inline hashval_t
999 tm_mem_map_hasher::hash (const value_type *v)
1001 return (intptr_t)v->val >> 4;
1004 inline bool
1005 tm_mem_map_hasher::equal (const value_type *v, const compare_type *c)
1007 return v->val == c->val;
1010 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1011 of memory (malloc, alloc, etc). */
1012 static hash_table <tm_mem_map_hasher> tm_new_mem_hash;
1014 /* Initialize logging data structures. */
1015 static void
1016 tm_log_init (void)
1018 tm_log.create (10);
1019 tm_new_mem_hash.create (5);
1020 tm_log_save_addresses.create (5);
1023 /* Free logging data structures. */
1024 static void
1025 tm_log_delete (void)
1027 tm_log.dispose ();
1028 tm_new_mem_hash.dispose ();
1029 tm_log_save_addresses.release ();
1032 /* Return true if MEM is a transaction invariant memory for the TM
1033 region starting at REGION_ENTRY_BLOCK. */
1034 static bool
1035 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1037 if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1038 && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1040 basic_block def_bb;
1042 def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1043 return def_bb != region_entry_block
1044 && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1047 mem = strip_invariant_refs (mem);
1048 return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1051 /* Given an address ADDR in STMT, find it in the memory log or add it,
1052 making sure to keep only the addresses highest in the dominator
1053 tree.
1055 ENTRY_BLOCK is the entry_block for the transaction.
1057 If we find the address in the log, make sure it's either the same
1058 address, or an equivalent one that dominates ADDR.
1060 If we find the address, but neither ADDR dominates the found
1061 address, nor the found one dominates ADDR, we're on different
1062 execution paths. Add it.
1064 If known, ENTRY_BLOCK is the entry block for the region, otherwise
1065 NULL. */
1066 static void
1067 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1069 tm_log_entry **slot;
1070 struct tm_log_entry l, *lp;
1072 l.addr = addr;
1073 slot = tm_log.find_slot (&l, INSERT);
1074 if (!*slot)
1076 tree type = TREE_TYPE (addr);
1078 lp = XNEW (struct tm_log_entry);
1079 lp->addr = addr;
1080 *slot = lp;
1082 /* Small invariant addresses can be handled as save/restores. */
1083 if (entry_block
1084 && transaction_invariant_address_p (lp->addr, entry_block)
1085 && TYPE_SIZE_UNIT (type) != NULL
1086 && host_integerp (TYPE_SIZE_UNIT (type), 1)
1087 && (tree_low_cst (TYPE_SIZE_UNIT (type), 1)
1088 < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1089 /* We must be able to copy this type normally. I.e., no
1090 special constructors and the like. */
1091 && !TREE_ADDRESSABLE (type))
1093 lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1094 lp->stmts.create (0);
1095 lp->entry_block = entry_block;
1096 /* Save addresses separately in dominator order so we don't
1097 get confused by overlapping addresses in the save/restore
1098 sequence. */
1099 tm_log_save_addresses.safe_push (lp->addr);
1101 else
1103 /* Use the logging functions. */
1104 lp->stmts.create (5);
1105 lp->stmts.quick_push (stmt);
1106 lp->save_var = NULL;
1109 else
1111 size_t i;
1112 gimple oldstmt;
1114 lp = *slot;
1116 /* If we're generating a save/restore sequence, we don't care
1117 about statements. */
1118 if (lp->save_var)
1119 return;
1121 for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1123 if (stmt == oldstmt)
1124 return;
1125 /* We already have a store to the same address, higher up the
1126 dominator tree. Nothing to do. */
1127 if (dominated_by_p (CDI_DOMINATORS,
1128 gimple_bb (stmt), gimple_bb (oldstmt)))
1129 return;
1130 /* We should be processing blocks in dominator tree order. */
1131 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1132 gimple_bb (oldstmt), gimple_bb (stmt)));
1134 /* Store is on a different code path. */
1135 lp->stmts.safe_push (stmt);
1139 /* Gimplify the address of a TARGET_MEM_REF. Return the SSA_NAME
1140 result, insert the new statements before GSI. */
1142 static tree
1143 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1145 if (TREE_CODE (x) == TARGET_MEM_REF)
1146 x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1147 else
1148 x = build_fold_addr_expr (x);
1149 return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1152 /* Instrument one address with the logging functions.
1153 ADDR is the address to save.
1154 STMT is the statement before which to place it. */
1155 static void
1156 tm_log_emit_stmt (tree addr, gimple stmt)
1158 tree type = TREE_TYPE (addr);
1159 tree size = TYPE_SIZE_UNIT (type);
1160 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1161 gimple log;
1162 enum built_in_function code = BUILT_IN_TM_LOG;
1164 if (type == float_type_node)
1165 code = BUILT_IN_TM_LOG_FLOAT;
1166 else if (type == double_type_node)
1167 code = BUILT_IN_TM_LOG_DOUBLE;
1168 else if (type == long_double_type_node)
1169 code = BUILT_IN_TM_LOG_LDOUBLE;
1170 else if (host_integerp (size, 1))
1172 unsigned int n = tree_low_cst (size, 1);
1173 switch (n)
1175 case 1:
1176 code = BUILT_IN_TM_LOG_1;
1177 break;
1178 case 2:
1179 code = BUILT_IN_TM_LOG_2;
1180 break;
1181 case 4:
1182 code = BUILT_IN_TM_LOG_4;
1183 break;
1184 case 8:
1185 code = BUILT_IN_TM_LOG_8;
1186 break;
1187 default:
1188 code = BUILT_IN_TM_LOG;
1189 if (TREE_CODE (type) == VECTOR_TYPE)
1191 if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1192 code = BUILT_IN_TM_LOG_M64;
1193 else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1194 code = BUILT_IN_TM_LOG_M128;
1195 else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1196 code = BUILT_IN_TM_LOG_M256;
1198 break;
1202 addr = gimplify_addr (&gsi, addr);
1203 if (code == BUILT_IN_TM_LOG)
1204 log = gimple_build_call (builtin_decl_explicit (code), 2, addr, size);
1205 else
1206 log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1207 gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1210 /* Go through the log and instrument address that must be instrumented
1211 with the logging functions. Leave the save/restore addresses for
1212 later. */
1213 static void
1214 tm_log_emit (void)
1216 hash_table <log_entry_hasher>::iterator hi;
1217 struct tm_log_entry *lp;
1219 FOR_EACH_HASH_TABLE_ELEMENT (tm_log, lp, tm_log_entry_t, hi)
1221 size_t i;
1222 gimple stmt;
1224 if (dump_file)
1226 fprintf (dump_file, "TM thread private mem logging: ");
1227 print_generic_expr (dump_file, lp->addr, 0);
1228 fprintf (dump_file, "\n");
1231 if (lp->save_var)
1233 if (dump_file)
1234 fprintf (dump_file, "DUMPING to variable\n");
1235 continue;
1237 else
1239 if (dump_file)
1240 fprintf (dump_file, "DUMPING with logging functions\n");
1241 for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1242 tm_log_emit_stmt (lp->addr, stmt);
1247 /* Emit the save sequence for the corresponding addresses in the log.
1248 ENTRY_BLOCK is the entry block for the transaction.
1249 BB is the basic block to insert the code in. */
1250 static void
1251 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1253 size_t i;
1254 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1255 gimple stmt;
1256 struct tm_log_entry l, *lp;
1258 for (i = 0; i < tm_log_save_addresses.length (); ++i)
1260 l.addr = tm_log_save_addresses[i];
1261 lp = *(tm_log.find_slot (&l, NO_INSERT));
1262 gcc_assert (lp->save_var != NULL);
1264 /* We only care about variables in the current transaction. */
1265 if (lp->entry_block != entry_block)
1266 continue;
1268 stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1270 /* Make sure we can create an SSA_NAME for this type. For
1271 instance, aggregates aren't allowed, in which case the system
1272 will create a VOP for us and everything will just work. */
1273 if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1275 lp->save_var = make_ssa_name (lp->save_var, stmt);
1276 gimple_assign_set_lhs (stmt, lp->save_var);
1279 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1283 /* Emit the restore sequence for the corresponding addresses in the log.
1284 ENTRY_BLOCK is the entry block for the transaction.
1285 BB is the basic block to insert the code in. */
1286 static void
1287 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1289 int i;
1290 struct tm_log_entry l, *lp;
1291 gimple_stmt_iterator gsi;
1292 gimple stmt;
1294 for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1296 l.addr = tm_log_save_addresses[i];
1297 lp = *(tm_log.find_slot (&l, NO_INSERT));
1298 gcc_assert (lp->save_var != NULL);
1300 /* We only care about variables in the current transaction. */
1301 if (lp->entry_block != entry_block)
1302 continue;
1304 /* Restores are in LIFO order from the saves in case we have
1305 overlaps. */
1306 gsi = gsi_start_bb (bb);
1308 stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1309 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1314 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1315 struct walk_stmt_info *);
1316 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1317 struct walk_stmt_info *);
1319 /* Evaluate an address X being dereferenced and determine if it
1320 originally points to a non aliased new chunk of memory (malloc,
1321 alloca, etc).
1323 Return MEM_THREAD_LOCAL if it points to a thread-local address.
1324 Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1325 Return MEM_NON_LOCAL otherwise.
1327 ENTRY_BLOCK is the entry block to the transaction containing the
1328 dereference of X. */
1329 static enum thread_memory_type
1330 thread_private_new_memory (basic_block entry_block, tree x)
1332 gimple stmt = NULL;
1333 enum tree_code code;
1334 tm_new_mem_map_t **slot;
1335 tm_new_mem_map_t elt, *elt_p;
1336 tree val = x;
1337 enum thread_memory_type retval = mem_transaction_local;
1339 if (!entry_block
1340 || TREE_CODE (x) != SSA_NAME
1341 /* Possible uninitialized use, or a function argument. In
1342 either case, we don't care. */
1343 || SSA_NAME_IS_DEFAULT_DEF (x))
1344 return mem_non_local;
1346 /* Look in cache first. */
1347 elt.val = x;
1348 slot = tm_new_mem_hash.find_slot (&elt, INSERT);
1349 elt_p = *slot;
1350 if (elt_p)
1351 return elt_p->local_new_memory;
1353 /* Optimistically assume the memory is transaction local during
1354 processing. This catches recursion into this variable. */
1355 *slot = elt_p = XNEW (tm_new_mem_map_t);
1356 elt_p->val = val;
1357 elt_p->local_new_memory = mem_transaction_local;
1359 /* Search DEF chain to find the original definition of this address. */
1362 if (ptr_deref_may_alias_global_p (x))
1364 /* Address escapes. This is not thread-private. */
1365 retval = mem_non_local;
1366 goto new_memory_ret;
1369 stmt = SSA_NAME_DEF_STMT (x);
1371 /* If the malloc call is outside the transaction, this is
1372 thread-local. */
1373 if (retval != mem_thread_local
1374 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1375 retval = mem_thread_local;
1377 if (is_gimple_assign (stmt))
1379 code = gimple_assign_rhs_code (stmt);
1380 /* x = foo ==> foo */
1381 if (code == SSA_NAME)
1382 x = gimple_assign_rhs1 (stmt);
1383 /* x = foo + n ==> foo */
1384 else if (code == POINTER_PLUS_EXPR)
1385 x = gimple_assign_rhs1 (stmt);
1386 /* x = (cast*) foo ==> foo */
1387 else if (code == VIEW_CONVERT_EXPR || code == NOP_EXPR)
1388 x = gimple_assign_rhs1 (stmt);
1389 /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1390 else if (code == COND_EXPR)
1392 tree op1 = gimple_assign_rhs2 (stmt);
1393 tree op2 = gimple_assign_rhs3 (stmt);
1394 enum thread_memory_type mem;
1395 retval = thread_private_new_memory (entry_block, op1);
1396 if (retval == mem_non_local)
1397 goto new_memory_ret;
1398 mem = thread_private_new_memory (entry_block, op2);
1399 retval = MIN (retval, mem);
1400 goto new_memory_ret;
1402 else
1404 retval = mem_non_local;
1405 goto new_memory_ret;
1408 else
1410 if (gimple_code (stmt) == GIMPLE_PHI)
1412 unsigned int i;
1413 enum thread_memory_type mem;
1414 tree phi_result = gimple_phi_result (stmt);
1416 /* If any of the ancestors are non-local, we are sure to
1417 be non-local. Otherwise we can avoid doing anything
1418 and inherit what has already been generated. */
1419 retval = mem_max;
1420 for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1422 tree op = PHI_ARG_DEF (stmt, i);
1424 /* Exclude self-assignment. */
1425 if (phi_result == op)
1426 continue;
1428 mem = thread_private_new_memory (entry_block, op);
1429 if (mem == mem_non_local)
1431 retval = mem;
1432 goto new_memory_ret;
1434 retval = MIN (retval, mem);
1436 goto new_memory_ret;
1438 break;
1441 while (TREE_CODE (x) == SSA_NAME);
1443 if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1444 /* Thread-local or transaction-local. */
1446 else
1447 retval = mem_non_local;
1449 new_memory_ret:
1450 elt_p->local_new_memory = retval;
1451 return retval;
1454 /* Determine whether X has to be instrumented using a read
1455 or write barrier.
1457 ENTRY_BLOCK is the entry block for the region where stmt resides
1458 in. NULL if unknown.
1460 STMT is the statement in which X occurs in. It is used for thread
1461 private memory instrumentation. If no TPM instrumentation is
1462 desired, STMT should be null. */
1463 static bool
1464 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1466 tree orig = x;
1467 while (handled_component_p (x))
1468 x = TREE_OPERAND (x, 0);
1470 switch (TREE_CODE (x))
1472 case INDIRECT_REF:
1473 case MEM_REF:
1475 enum thread_memory_type ret;
1477 ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1478 if (ret == mem_non_local)
1479 return true;
1480 if (stmt && ret == mem_thread_local)
1481 /* ?? Should we pass `orig', or the INDIRECT_REF X. ?? */
1482 tm_log_add (entry_block, orig, stmt);
1484 /* Transaction-locals require nothing at all. For malloc, a
1485 transaction restart frees the memory and we reallocate.
1486 For alloca, the stack pointer gets reset by the retry and
1487 we reallocate. */
1488 return false;
1491 case TARGET_MEM_REF:
1492 if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1493 return true;
1494 x = TREE_OPERAND (TMR_BASE (x), 0);
1495 if (TREE_CODE (x) == PARM_DECL)
1496 return false;
1497 gcc_assert (TREE_CODE (x) == VAR_DECL);
1498 /* FALLTHRU */
1500 case PARM_DECL:
1501 case RESULT_DECL:
1502 case VAR_DECL:
1503 if (DECL_BY_REFERENCE (x))
1505 /* ??? This value is a pointer, but aggregate_value_p has been
1506 jigged to return true which confuses needs_to_live_in_memory.
1507 This ought to be cleaned up generically.
1509 FIXME: Verify this still happens after the next mainline
1510 merge. Testcase ie g++.dg/tm/pr47554.C.
1512 return false;
1515 if (is_global_var (x))
1516 return !TREE_READONLY (x);
1517 if (/* FIXME: This condition should actually go below in the
1518 tm_log_add() call, however is_call_clobbered() depends on
1519 aliasing info which is not available during
1520 gimplification. Since requires_barrier() gets called
1521 during lower_sequence_tm/gimplification, leave the call
1522 to needs_to_live_in_memory until we eliminate
1523 lower_sequence_tm altogether. */
1524 needs_to_live_in_memory (x))
1525 return true;
1526 else
1528 /* For local memory that doesn't escape (aka thread private
1529 memory), we can either save the value at the beginning of
1530 the transaction and restore on restart, or call a tm
1531 function to dynamically save and restore on restart
1532 (ITM_L*). */
1533 if (stmt)
1534 tm_log_add (entry_block, orig, stmt);
1535 return false;
1538 default:
1539 return false;
1543 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1544 a transaction region. */
1546 static void
1547 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1549 gimple stmt = gsi_stmt (*gsi);
1551 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1552 *state |= GTMA_HAVE_LOAD;
1553 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1554 *state |= GTMA_HAVE_STORE;
1557 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction. */
1559 static void
1560 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1562 gimple stmt = gsi_stmt (*gsi);
1563 tree fn;
1565 if (is_tm_pure_call (stmt))
1566 return;
1568 /* Check if this call is a transaction abort. */
1569 fn = gimple_call_fndecl (stmt);
1570 if (is_tm_abort (fn))
1571 *state |= GTMA_HAVE_ABORT;
1573 /* Note that something may happen. */
1574 *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1577 /* Lower a GIMPLE_TRANSACTION statement. */
1579 static void
1580 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1582 gimple g, stmt = gsi_stmt (*gsi);
1583 unsigned int *outer_state = (unsigned int *) wi->info;
1584 unsigned int this_state = 0;
1585 struct walk_stmt_info this_wi;
1587 /* First, lower the body. The scanning that we do inside gives
1588 us some idea of what we're dealing with. */
1589 memset (&this_wi, 0, sizeof (this_wi));
1590 this_wi.info = (void *) &this_state;
1591 walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1592 lower_sequence_tm, NULL, &this_wi);
1594 /* If there was absolutely nothing transaction related inside the
1595 transaction, we may elide it. Likewise if this is a nested
1596 transaction and does not contain an abort. */
1597 if (this_state == 0
1598 || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1600 if (outer_state)
1601 *outer_state |= this_state;
1603 gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1604 GSI_SAME_STMT);
1605 gimple_transaction_set_body (stmt, NULL);
1607 gsi_remove (gsi, true);
1608 wi->removed_stmt = true;
1609 return;
1612 /* Wrap the body of the transaction in a try-finally node so that
1613 the commit call is always properly called. */
1614 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1615 if (flag_exceptions)
1617 tree ptr;
1618 gimple_seq n_seq, e_seq;
1620 n_seq = gimple_seq_alloc_with_stmt (g);
1621 e_seq = NULL;
1623 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1624 1, integer_zero_node);
1625 ptr = create_tmp_var (ptr_type_node, NULL);
1626 gimple_call_set_lhs (g, ptr);
1627 gimple_seq_add_stmt (&e_seq, g);
1629 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1630 1, ptr);
1631 gimple_seq_add_stmt (&e_seq, g);
1633 g = gimple_build_eh_else (n_seq, e_seq);
1636 g = gimple_build_try (gimple_transaction_body (stmt),
1637 gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1638 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1640 gimple_transaction_set_body (stmt, NULL);
1642 /* If the transaction calls abort or if this is an outer transaction,
1643 add an "over" label afterwards. */
1644 if ((this_state & (GTMA_HAVE_ABORT))
1645 || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1647 tree label = create_artificial_label (UNKNOWN_LOCATION);
1648 gimple_transaction_set_label (stmt, label);
1649 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1652 /* Record the set of operations found for use later. */
1653 this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1654 gimple_transaction_set_subcode (stmt, this_state);
1657 /* Iterate through the statements in the sequence, lowering them all
1658 as appropriate for being in a transaction. */
1660 static tree
1661 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1662 struct walk_stmt_info *wi)
1664 unsigned int *state = (unsigned int *) wi->info;
1665 gimple stmt = gsi_stmt (*gsi);
1667 *handled_ops_p = true;
1668 switch (gimple_code (stmt))
1670 case GIMPLE_ASSIGN:
1671 /* Only memory reads/writes need to be instrumented. */
1672 if (gimple_assign_single_p (stmt))
1673 examine_assign_tm (state, gsi);
1674 break;
1676 case GIMPLE_CALL:
1677 examine_call_tm (state, gsi);
1678 break;
1680 case GIMPLE_ASM:
1681 *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1682 break;
1684 case GIMPLE_TRANSACTION:
1685 lower_transaction (gsi, wi);
1686 break;
1688 default:
1689 *handled_ops_p = !gimple_has_substatements (stmt);
1690 break;
1693 return NULL_TREE;
1696 /* Iterate through the statements in the sequence, lowering them all
1697 as appropriate for being outside of a transaction. */
1699 static tree
1700 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1701 struct walk_stmt_info * wi)
1703 gimple stmt = gsi_stmt (*gsi);
1705 if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1707 *handled_ops_p = true;
1708 lower_transaction (gsi, wi);
1710 else
1711 *handled_ops_p = !gimple_has_substatements (stmt);
1713 return NULL_TREE;
1716 /* Main entry point for flattening GIMPLE_TRANSACTION constructs. After
1717 this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1718 been moved out, and all the data required for constructing a proper
1719 CFG has been recorded. */
1721 static unsigned int
1722 execute_lower_tm (void)
1724 struct walk_stmt_info wi;
1725 gimple_seq body;
1727 /* Transactional clones aren't created until a later pass. */
1728 gcc_assert (!decl_is_tm_clone (current_function_decl));
1730 body = gimple_body (current_function_decl);
1731 memset (&wi, 0, sizeof (wi));
1732 walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1733 gimple_set_body (current_function_decl, body);
1735 return 0;
1738 namespace {
1740 const pass_data pass_data_lower_tm =
1742 GIMPLE_PASS, /* type */
1743 "tmlower", /* name */
1744 OPTGROUP_NONE, /* optinfo_flags */
1745 true, /* has_gate */
1746 true, /* has_execute */
1747 TV_TRANS_MEM, /* tv_id */
1748 PROP_gimple_lcf, /* properties_required */
1749 0, /* properties_provided */
1750 0, /* properties_destroyed */
1751 0, /* todo_flags_start */
1752 0, /* todo_flags_finish */
1755 class pass_lower_tm : public gimple_opt_pass
1757 public:
1758 pass_lower_tm (gcc::context *ctxt)
1759 : gimple_opt_pass (pass_data_lower_tm, ctxt)
1762 /* opt_pass methods: */
1763 bool gate () { return gate_tm (); }
1764 unsigned int execute () { return execute_lower_tm (); }
1766 }; // class pass_lower_tm
1768 } // anon namespace
1770 gimple_opt_pass *
1771 make_pass_lower_tm (gcc::context *ctxt)
1773 return new pass_lower_tm (ctxt);
1776 /* Collect region information for each transaction. */
1778 struct tm_region
1780 /* Link to the next unnested transaction. */
1781 struct tm_region *next;
1783 /* Link to the next inner transaction. */
1784 struct tm_region *inner;
1786 /* Link to the next outer transaction. */
1787 struct tm_region *outer;
1789 /* The GIMPLE_TRANSACTION statement beginning this transaction.
1790 After TM_MARK, this gets replaced by a call to
1791 BUILT_IN_TM_START. */
1792 gimple transaction_stmt;
1794 /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1795 BUILT_IN_TM_START, this field is true if the transaction is an
1796 outer transaction. */
1797 bool original_transaction_was_outer;
1799 /* Return value from BUILT_IN_TM_START. */
1800 tree tm_state;
1802 /* The entry block to this region. This will always be the first
1803 block of the body of the transaction. */
1804 basic_block entry_block;
1806 /* The first block after an expanded call to _ITM_beginTransaction. */
1807 basic_block restart_block;
1809 /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1810 These blocks are still a part of the region (i.e., the border is
1811 inclusive). Note that this set is only complete for paths in the CFG
1812 starting at ENTRY_BLOCK, and that there is no exit block recorded for
1813 the edge to the "over" label. */
1814 bitmap exit_blocks;
1816 /* The set of all blocks that have an TM_IRREVOCABLE call. */
1817 bitmap irr_blocks;
1820 typedef struct tm_region *tm_region_p;
1822 /* True if there are pending edge statements to be committed for the
1823 current function being scanned in the tmmark pass. */
1824 bool pending_edge_inserts_p;
1826 static struct tm_region *all_tm_regions;
1827 static bitmap_obstack tm_obstack;
1830 /* A subroutine of tm_region_init. Record the existence of the
1831 GIMPLE_TRANSACTION statement in a tree of tm_region elements. */
1833 static struct tm_region *
1834 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1836 struct tm_region *region;
1838 region = (struct tm_region *)
1839 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1841 if (outer)
1843 region->next = outer->inner;
1844 outer->inner = region;
1846 else
1848 region->next = all_tm_regions;
1849 all_tm_regions = region;
1851 region->inner = NULL;
1852 region->outer = outer;
1854 region->transaction_stmt = stmt;
1855 region->original_transaction_was_outer = false;
1856 region->tm_state = NULL;
1858 /* There are either one or two edges out of the block containing
1859 the GIMPLE_TRANSACTION, one to the actual region and one to the
1860 "over" label if the region contains an abort. The former will
1861 always be the one marked FALLTHRU. */
1862 region->entry_block = FALLTHRU_EDGE (bb)->dest;
1864 region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1865 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1867 return region;
1870 /* A subroutine of tm_region_init. Record all the exit and
1871 irrevocable blocks in BB into the region's exit_blocks and
1872 irr_blocks bitmaps. Returns the new region being scanned. */
1874 static struct tm_region *
1875 tm_region_init_1 (struct tm_region *region, basic_block bb)
1877 gimple_stmt_iterator gsi;
1878 gimple g;
1880 if (!region
1881 || (!region->irr_blocks && !region->exit_blocks))
1882 return region;
1884 /* Check to see if this is the end of a region by seeing if it
1885 contains a call to __builtin_tm_commit{,_eh}. Note that the
1886 outermost region for DECL_IS_TM_CLONE need not collect this. */
1887 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1889 g = gsi_stmt (gsi);
1890 if (gimple_code (g) == GIMPLE_CALL)
1892 tree fn = gimple_call_fndecl (g);
1893 if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1895 if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1896 || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1897 && region->exit_blocks)
1899 bitmap_set_bit (region->exit_blocks, bb->index);
1900 region = region->outer;
1901 break;
1903 if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1904 bitmap_set_bit (region->irr_blocks, bb->index);
1908 return region;
1911 /* Collect all of the transaction regions within the current function
1912 and record them in ALL_TM_REGIONS. The REGION parameter may specify
1913 an "outermost" region for use by tm clones. */
1915 static void
1916 tm_region_init (struct tm_region *region)
1918 gimple g;
1919 edge_iterator ei;
1920 edge e;
1921 basic_block bb;
1922 vec<basic_block> queue = vNULL;
1923 bitmap visited_blocks = BITMAP_ALLOC (NULL);
1924 struct tm_region *old_region;
1925 vec<tm_region_p> bb_regions = vNULL;
1927 all_tm_regions = region;
1928 bb = single_succ (ENTRY_BLOCK_PTR);
1930 /* We could store this information in bb->aux, but we may get called
1931 through get_all_tm_blocks() from another pass that may be already
1932 using bb->aux. */
1933 bb_regions.safe_grow_cleared (last_basic_block);
1935 queue.safe_push (bb);
1936 bb_regions[bb->index] = region;
1939 bb = queue.pop ();
1940 region = bb_regions[bb->index];
1941 bb_regions[bb->index] = NULL;
1943 /* Record exit and irrevocable blocks. */
1944 region = tm_region_init_1 (region, bb);
1946 /* Check for the last statement in the block beginning a new region. */
1947 g = last_stmt (bb);
1948 old_region = region;
1949 if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1950 region = tm_region_init_0 (region, bb, g);
1952 /* Process subsequent blocks. */
1953 FOR_EACH_EDGE (e, ei, bb->succs)
1954 if (!bitmap_bit_p (visited_blocks, e->dest->index))
1956 bitmap_set_bit (visited_blocks, e->dest->index);
1957 queue.safe_push (e->dest);
1959 /* If the current block started a new region, make sure that only
1960 the entry block of the new region is associated with this region.
1961 Other successors are still part of the old region. */
1962 if (old_region != region && e->dest != region->entry_block)
1963 bb_regions[e->dest->index] = old_region;
1964 else
1965 bb_regions[e->dest->index] = region;
1968 while (!queue.is_empty ());
1969 queue.release ();
1970 BITMAP_FREE (visited_blocks);
1971 bb_regions.release ();
1974 /* The "gate" function for all transactional memory expansion and optimization
1975 passes. We collect region information for each top-level transaction, and
1976 if we don't find any, we skip all of the TM passes. Each region will have
1977 all of the exit blocks recorded, and the originating statement. */
1979 static bool
1980 gate_tm_init (void)
1982 if (!flag_tm)
1983 return false;
1985 calculate_dominance_info (CDI_DOMINATORS);
1986 bitmap_obstack_initialize (&tm_obstack);
1988 /* If the function is a TM_CLONE, then the entire function is the region. */
1989 if (decl_is_tm_clone (current_function_decl))
1991 struct tm_region *region = (struct tm_region *)
1992 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1993 memset (region, 0, sizeof (*region));
1994 region->entry_block = single_succ (ENTRY_BLOCK_PTR);
1995 /* For a clone, the entire function is the region. But even if
1996 we don't need to record any exit blocks, we may need to
1997 record irrevocable blocks. */
1998 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
2000 tm_region_init (region);
2002 else
2004 tm_region_init (NULL);
2006 /* If we didn't find any regions, cleanup and skip the whole tree
2007 of tm-related optimizations. */
2008 if (all_tm_regions == NULL)
2010 bitmap_obstack_release (&tm_obstack);
2011 return false;
2015 return true;
2018 namespace {
2020 const pass_data pass_data_tm_init =
2022 GIMPLE_PASS, /* type */
2023 "*tminit", /* name */
2024 OPTGROUP_NONE, /* optinfo_flags */
2025 true, /* has_gate */
2026 false, /* has_execute */
2027 TV_TRANS_MEM, /* tv_id */
2028 ( PROP_ssa | PROP_cfg ), /* properties_required */
2029 0, /* properties_provided */
2030 0, /* properties_destroyed */
2031 0, /* todo_flags_start */
2032 0, /* todo_flags_finish */
2035 class pass_tm_init : public gimple_opt_pass
2037 public:
2038 pass_tm_init (gcc::context *ctxt)
2039 : gimple_opt_pass (pass_data_tm_init, ctxt)
2042 /* opt_pass methods: */
2043 bool gate () { return gate_tm_init (); }
2045 }; // class pass_tm_init
2047 } // anon namespace
2049 gimple_opt_pass *
2050 make_pass_tm_init (gcc::context *ctxt)
2052 return new pass_tm_init (ctxt);
2055 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2056 represented by STATE. */
2058 static inline void
2059 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2061 if (region && region->transaction_stmt)
2063 flags |= gimple_transaction_subcode (region->transaction_stmt);
2064 gimple_transaction_set_subcode (region->transaction_stmt, flags);
2068 /* Construct a memory load in a transactional context. Return the
2069 gimple statement performing the load, or NULL if there is no
2070 TM_LOAD builtin of the appropriate size to do the load.
2072 LOC is the location to use for the new statement(s). */
2074 static gimple
2075 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2077 enum built_in_function code = END_BUILTINS;
2078 tree t, type = TREE_TYPE (rhs), decl;
2079 gimple gcall;
2081 if (type == float_type_node)
2082 code = BUILT_IN_TM_LOAD_FLOAT;
2083 else if (type == double_type_node)
2084 code = BUILT_IN_TM_LOAD_DOUBLE;
2085 else if (type == long_double_type_node)
2086 code = BUILT_IN_TM_LOAD_LDOUBLE;
2087 else if (TYPE_SIZE_UNIT (type) != NULL
2088 && host_integerp (TYPE_SIZE_UNIT (type), 1))
2090 switch (tree_low_cst (TYPE_SIZE_UNIT (type), 1))
2092 case 1:
2093 code = BUILT_IN_TM_LOAD_1;
2094 break;
2095 case 2:
2096 code = BUILT_IN_TM_LOAD_2;
2097 break;
2098 case 4:
2099 code = BUILT_IN_TM_LOAD_4;
2100 break;
2101 case 8:
2102 code = BUILT_IN_TM_LOAD_8;
2103 break;
2107 if (code == END_BUILTINS)
2109 decl = targetm.vectorize.builtin_tm_load (type);
2110 if (!decl)
2111 return NULL;
2113 else
2114 decl = builtin_decl_explicit (code);
2116 t = gimplify_addr (gsi, rhs);
2117 gcall = gimple_build_call (decl, 1, t);
2118 gimple_set_location (gcall, loc);
2120 t = TREE_TYPE (TREE_TYPE (decl));
2121 if (useless_type_conversion_p (type, t))
2123 gimple_call_set_lhs (gcall, lhs);
2124 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2126 else
2128 gimple g;
2129 tree temp;
2131 temp = create_tmp_reg (t, NULL);
2132 gimple_call_set_lhs (gcall, temp);
2133 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2135 t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2136 g = gimple_build_assign (lhs, t);
2137 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2140 return gcall;
2144 /* Similarly for storing TYPE in a transactional context. */
2146 static gimple
2147 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2149 enum built_in_function code = END_BUILTINS;
2150 tree t, fn, type = TREE_TYPE (rhs), simple_type;
2151 gimple gcall;
2153 if (type == float_type_node)
2154 code = BUILT_IN_TM_STORE_FLOAT;
2155 else if (type == double_type_node)
2156 code = BUILT_IN_TM_STORE_DOUBLE;
2157 else if (type == long_double_type_node)
2158 code = BUILT_IN_TM_STORE_LDOUBLE;
2159 else if (TYPE_SIZE_UNIT (type) != NULL
2160 && host_integerp (TYPE_SIZE_UNIT (type), 1))
2162 switch (tree_low_cst (TYPE_SIZE_UNIT (type), 1))
2164 case 1:
2165 code = BUILT_IN_TM_STORE_1;
2166 break;
2167 case 2:
2168 code = BUILT_IN_TM_STORE_2;
2169 break;
2170 case 4:
2171 code = BUILT_IN_TM_STORE_4;
2172 break;
2173 case 8:
2174 code = BUILT_IN_TM_STORE_8;
2175 break;
2179 if (code == END_BUILTINS)
2181 fn = targetm.vectorize.builtin_tm_store (type);
2182 if (!fn)
2183 return NULL;
2185 else
2186 fn = builtin_decl_explicit (code);
2188 simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2190 if (TREE_CODE (rhs) == CONSTRUCTOR)
2192 /* Handle the easy initialization to zero. */
2193 if (!CONSTRUCTOR_ELTS (rhs))
2194 rhs = build_int_cst (simple_type, 0);
2195 else
2197 /* ...otherwise punt to the caller and probably use
2198 BUILT_IN_TM_MEMMOVE, because we can't wrap a
2199 VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2200 valid gimple. */
2201 return NULL;
2204 else if (!useless_type_conversion_p (simple_type, type))
2206 gimple g;
2207 tree temp;
2209 temp = create_tmp_reg (simple_type, NULL);
2210 t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2211 g = gimple_build_assign (temp, t);
2212 gimple_set_location (g, loc);
2213 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2215 rhs = temp;
2218 t = gimplify_addr (gsi, lhs);
2219 gcall = gimple_build_call (fn, 2, t, rhs);
2220 gimple_set_location (gcall, loc);
2221 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2223 return gcall;
2227 /* Expand an assignment statement into transactional builtins. */
2229 static void
2230 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2232 gimple stmt = gsi_stmt (*gsi);
2233 location_t loc = gimple_location (stmt);
2234 tree lhs = gimple_assign_lhs (stmt);
2235 tree rhs = gimple_assign_rhs1 (stmt);
2236 bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2237 bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2238 gimple gcall = NULL;
2240 if (!load_p && !store_p)
2242 /* Add thread private addresses to log if applicable. */
2243 requires_barrier (region->entry_block, lhs, stmt);
2244 gsi_next (gsi);
2245 return;
2248 // Remove original load/store statement.
2249 gsi_remove (gsi, true);
2251 if (load_p && !store_p)
2253 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2254 gcall = build_tm_load (loc, lhs, rhs, gsi);
2256 else if (store_p && !load_p)
2258 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2259 gcall = build_tm_store (loc, lhs, rhs, gsi);
2261 if (!gcall)
2263 tree lhs_addr, rhs_addr, tmp;
2265 if (load_p)
2266 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2267 if (store_p)
2268 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2270 /* ??? Figure out if there's any possible overlap between the LHS
2271 and the RHS and if not, use MEMCPY. */
2273 if (load_p && is_gimple_reg (lhs))
2275 tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2276 lhs_addr = build_fold_addr_expr (tmp);
2278 else
2280 tmp = NULL_TREE;
2281 lhs_addr = gimplify_addr (gsi, lhs);
2283 rhs_addr = gimplify_addr (gsi, rhs);
2284 gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2285 3, lhs_addr, rhs_addr,
2286 TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2287 gimple_set_location (gcall, loc);
2288 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2290 if (tmp)
2292 gcall = gimple_build_assign (lhs, tmp);
2293 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2297 /* Now that we have the load/store in its instrumented form, add
2298 thread private addresses to the log if applicable. */
2299 if (!store_p)
2300 requires_barrier (region->entry_block, lhs, gcall);
2302 // The calls to build_tm_{store,load} above inserted the instrumented
2303 // call into the stream.
2304 // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2308 /* Expand a call statement as appropriate for a transaction. That is,
2309 either verify that the call does not affect the transaction, or
2310 redirect the call to a clone that handles transactions, or change
2311 the transaction state to IRREVOCABLE. Return true if the call is
2312 one of the builtins that end a transaction. */
2314 static bool
2315 expand_call_tm (struct tm_region *region,
2316 gimple_stmt_iterator *gsi)
2318 gimple stmt = gsi_stmt (*gsi);
2319 tree lhs = gimple_call_lhs (stmt);
2320 tree fn_decl;
2321 struct cgraph_node *node;
2322 bool retval = false;
2324 fn_decl = gimple_call_fndecl (stmt);
2326 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2327 || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2328 transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2329 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2330 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2332 if (is_tm_pure_call (stmt))
2333 return false;
2335 if (fn_decl)
2336 retval = is_tm_ending_fndecl (fn_decl);
2337 if (!retval)
2339 /* Assume all non-const/pure calls write to memory, except
2340 transaction ending builtins. */
2341 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2344 /* For indirect calls, we already generated a call into the runtime. */
2345 if (!fn_decl)
2347 tree fn = gimple_call_fn (stmt);
2349 /* We are guaranteed never to go irrevocable on a safe or pure
2350 call, and the pure call was handled above. */
2351 if (is_tm_safe (fn))
2352 return false;
2353 else
2354 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2356 return false;
2359 node = cgraph_get_node (fn_decl);
2360 /* All calls should have cgraph here. */
2361 if (!node)
2363 /* We can have a nodeless call here if some pass after IPA-tm
2364 added uninstrumented calls. For example, loop distribution
2365 can transform certain loop constructs into __builtin_mem*
2366 calls. In this case, see if we have a suitable TM
2367 replacement and fill in the gaps. */
2368 gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2369 enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2370 gcc_assert (code == BUILT_IN_MEMCPY
2371 || code == BUILT_IN_MEMMOVE
2372 || code == BUILT_IN_MEMSET);
2374 tree repl = find_tm_replacement_function (fn_decl);
2375 if (repl)
2377 gimple_call_set_fndecl (stmt, repl);
2378 update_stmt (stmt);
2379 node = cgraph_create_node (repl);
2380 node->local.tm_may_enter_irr = false;
2381 return expand_call_tm (region, gsi);
2383 gcc_unreachable ();
2385 if (node->local.tm_may_enter_irr)
2386 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2388 if (is_tm_abort (fn_decl))
2390 transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2391 return true;
2394 /* Instrument the store if needed.
2396 If the assignment happens inside the function call (return slot
2397 optimization), there is no instrumentation to be done, since
2398 the callee should have done the right thing. */
2399 if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2400 && !gimple_call_return_slot_opt_p (stmt))
2402 tree tmp = create_tmp_reg (TREE_TYPE (lhs), NULL);
2403 location_t loc = gimple_location (stmt);
2404 edge fallthru_edge = NULL;
2406 /* Remember if the call was going to throw. */
2407 if (stmt_can_throw_internal (stmt))
2409 edge_iterator ei;
2410 edge e;
2411 basic_block bb = gimple_bb (stmt);
2413 FOR_EACH_EDGE (e, ei, bb->succs)
2414 if (e->flags & EDGE_FALLTHRU)
2416 fallthru_edge = e;
2417 break;
2421 gimple_call_set_lhs (stmt, tmp);
2422 update_stmt (stmt);
2423 stmt = gimple_build_assign (lhs, tmp);
2424 gimple_set_location (stmt, loc);
2426 /* We cannot throw in the middle of a BB. If the call was going
2427 to throw, place the instrumentation on the fallthru edge, so
2428 the call remains the last statement in the block. */
2429 if (fallthru_edge)
2431 gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2432 gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2433 expand_assign_tm (region, &fallthru_gsi);
2434 gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2435 pending_edge_inserts_p = true;
2437 else
2439 gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2440 expand_assign_tm (region, gsi);
2443 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2446 return retval;
2450 /* Expand all statements in BB as appropriate for being inside
2451 a transaction. */
2453 static void
2454 expand_block_tm (struct tm_region *region, basic_block bb)
2456 gimple_stmt_iterator gsi;
2458 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2460 gimple stmt = gsi_stmt (gsi);
2461 switch (gimple_code (stmt))
2463 case GIMPLE_ASSIGN:
2464 /* Only memory reads/writes need to be instrumented. */
2465 if (gimple_assign_single_p (stmt)
2466 && !gimple_clobber_p (stmt))
2468 expand_assign_tm (region, &gsi);
2469 continue;
2471 break;
2473 case GIMPLE_CALL:
2474 if (expand_call_tm (region, &gsi))
2475 return;
2476 break;
2478 case GIMPLE_ASM:
2479 gcc_unreachable ();
2481 default:
2482 break;
2484 if (!gsi_end_p (gsi))
2485 gsi_next (&gsi);
2489 /* Return the list of basic-blocks in REGION.
2491 STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2492 following a TM_IRREVOCABLE call.
2494 INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2495 uninstrumented code path blocks in the list of basic blocks
2496 returned, false otherwise. */
2498 static vec<basic_block>
2499 get_tm_region_blocks (basic_block entry_block,
2500 bitmap exit_blocks,
2501 bitmap irr_blocks,
2502 bitmap all_region_blocks,
2503 bool stop_at_irrevocable_p,
2504 bool include_uninstrumented_p = true)
2506 vec<basic_block> bbs = vNULL;
2507 unsigned i;
2508 edge e;
2509 edge_iterator ei;
2510 bitmap visited_blocks = BITMAP_ALLOC (NULL);
2512 i = 0;
2513 bbs.safe_push (entry_block);
2514 bitmap_set_bit (visited_blocks, entry_block->index);
2518 basic_block bb = bbs[i++];
2520 if (exit_blocks &&
2521 bitmap_bit_p (exit_blocks, bb->index))
2522 continue;
2524 if (stop_at_irrevocable_p
2525 && irr_blocks
2526 && bitmap_bit_p (irr_blocks, bb->index))
2527 continue;
2529 FOR_EACH_EDGE (e, ei, bb->succs)
2530 if ((include_uninstrumented_p
2531 || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2532 && !bitmap_bit_p (visited_blocks, e->dest->index))
2534 bitmap_set_bit (visited_blocks, e->dest->index);
2535 bbs.safe_push (e->dest);
2538 while (i < bbs.length ());
2540 if (all_region_blocks)
2541 bitmap_ior_into (all_region_blocks, visited_blocks);
2543 BITMAP_FREE (visited_blocks);
2544 return bbs;
2547 // Callback data for collect_bb2reg.
2548 struct bb2reg_stuff
2550 vec<tm_region_p> *bb2reg;
2551 bool include_uninstrumented_p;
2554 // Callback for expand_regions, collect innermost region data for each bb.
2555 static void *
2556 collect_bb2reg (struct tm_region *region, void *data)
2558 struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2559 vec<tm_region_p> *bb2reg = stuff->bb2reg;
2560 vec<basic_block> queue;
2561 unsigned int i;
2562 basic_block bb;
2564 queue = get_tm_region_blocks (region->entry_block,
2565 region->exit_blocks,
2566 region->irr_blocks,
2567 NULL,
2568 /*stop_at_irr_p=*/true,
2569 stuff->include_uninstrumented_p);
2571 // We expect expand_region to perform a post-order traversal of the region
2572 // tree. Therefore the last region seen for any bb is the innermost.
2573 FOR_EACH_VEC_ELT (queue, i, bb)
2574 (*bb2reg)[bb->index] = region;
2576 queue.release ();
2577 return NULL;
2580 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2581 // which a basic block belongs. Note that we only consider the instrumented
2582 // code paths for the region; the uninstrumented code paths are ignored if
2583 // INCLUDE_UNINSTRUMENTED_P is false.
2585 // ??? This data is very similar to the bb_regions array that is collected
2586 // during tm_region_init. Or, rather, this data is similar to what could
2587 // be used within tm_region_init. The actual computation in tm_region_init
2588 // begins and ends with bb_regions entirely full of NULL pointers, due to
2589 // the way in which pointers are swapped in and out of the array.
2591 // ??? Our callers expect that blocks are not shared between transactions.
2592 // When the optimizers get too smart, and blocks are shared, then during
2593 // the tm_mark phase we'll add log entries to only one of the two transactions,
2594 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2595 // cycles. The symptom being SSA defs that do not dominate their uses.
2596 // Note that the optimizers were locally correct with their transformation,
2597 // as we have no info within the program that suggests that the blocks cannot
2598 // be shared.
2600 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2601 // only known instance of this block sharing.
2603 static vec<tm_region_p>
2604 get_bb_regions_instrumented (bool traverse_clones,
2605 bool include_uninstrumented_p)
2607 unsigned n = last_basic_block;
2608 struct bb2reg_stuff stuff;
2609 vec<tm_region_p> ret;
2611 ret.create (n);
2612 ret.safe_grow_cleared (n);
2613 stuff.bb2reg = &ret;
2614 stuff.include_uninstrumented_p = include_uninstrumented_p;
2615 expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2617 return ret;
2620 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2621 transaction. */
2623 void
2624 compute_transaction_bits (void)
2626 struct tm_region *region;
2627 vec<basic_block> queue;
2628 unsigned int i;
2629 basic_block bb;
2631 /* ?? Perhaps we need to abstract gate_tm_init further, because we
2632 certainly don't need it to calculate CDI_DOMINATOR info. */
2633 gate_tm_init ();
2635 FOR_EACH_BB (bb)
2636 bb->flags &= ~BB_IN_TRANSACTION;
2638 for (region = all_tm_regions; region; region = region->next)
2640 queue = get_tm_region_blocks (region->entry_block,
2641 region->exit_blocks,
2642 region->irr_blocks,
2643 NULL,
2644 /*stop_at_irr_p=*/true);
2645 for (i = 0; queue.iterate (i, &bb); ++i)
2646 bb->flags |= BB_IN_TRANSACTION;
2647 queue.release ();
2650 if (all_tm_regions)
2651 bitmap_obstack_release (&tm_obstack);
2654 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2655 call to BUILT_IN_TM_START. */
2657 static void *
2658 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2660 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2661 basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2662 tree tm_state = region->tm_state;
2663 tree tm_state_type = TREE_TYPE (tm_state);
2664 edge abort_edge = NULL;
2665 edge inst_edge = NULL;
2666 edge uninst_edge = NULL;
2667 edge fallthru_edge = NULL;
2669 // Identify the various successors of the transaction start.
2671 edge_iterator i;
2672 edge e;
2673 FOR_EACH_EDGE (e, i, transaction_bb->succs)
2675 if (e->flags & EDGE_TM_ABORT)
2676 abort_edge = e;
2677 else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2678 uninst_edge = e;
2679 else
2680 inst_edge = e;
2681 if (e->flags & EDGE_FALLTHRU)
2682 fallthru_edge = e;
2686 /* ??? There are plenty of bits here we're not computing. */
2688 int subcode = gimple_transaction_subcode (region->transaction_stmt);
2689 int flags = 0;
2690 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2691 flags |= PR_DOESGOIRREVOCABLE;
2692 if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2693 flags |= PR_HASNOIRREVOCABLE;
2694 /* If the transaction does not have an abort in lexical scope and is not
2695 marked as an outer transaction, then it will never abort. */
2696 if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2697 flags |= PR_HASNOABORT;
2698 if ((subcode & GTMA_HAVE_STORE) == 0)
2699 flags |= PR_READONLY;
2700 if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2701 flags |= PR_INSTRUMENTEDCODE;
2702 if (uninst_edge)
2703 flags |= PR_UNINSTRUMENTEDCODE;
2704 if (subcode & GTMA_IS_OUTER)
2705 region->original_transaction_was_outer = true;
2706 tree t = build_int_cst (tm_state_type, flags);
2707 gimple call = gimple_build_call (tm_start, 1, t);
2708 gimple_call_set_lhs (call, tm_state);
2709 gimple_set_location (call, gimple_location (region->transaction_stmt));
2711 // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2712 gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2713 gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2714 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2715 gsi_remove (&gsi, true);
2716 region->transaction_stmt = call;
2719 // Generate log saves.
2720 if (!tm_log_save_addresses.is_empty ())
2721 tm_log_emit_saves (region->entry_block, transaction_bb);
2723 // In the beginning, we've no tests to perform on transaction restart.
2724 // Note that after this point, transaction_bb becomes the "most recent
2725 // block containing tests for the transaction".
2726 region->restart_block = region->entry_block;
2728 // Generate log restores.
2729 if (!tm_log_save_addresses.is_empty ())
2731 basic_block test_bb = create_empty_bb (transaction_bb);
2732 basic_block code_bb = create_empty_bb (test_bb);
2733 basic_block join_bb = create_empty_bb (code_bb);
2734 if (current_loops && transaction_bb->loop_father)
2736 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2737 add_bb_to_loop (code_bb, transaction_bb->loop_father);
2738 add_bb_to_loop (join_bb, transaction_bb->loop_father);
2740 if (region->restart_block == region->entry_block)
2741 region->restart_block = test_bb;
2743 tree t1 = create_tmp_reg (tm_state_type, NULL);
2744 tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2745 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2746 tm_state, t2);
2747 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2748 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2750 t2 = build_int_cst (tm_state_type, 0);
2751 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2752 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2754 tm_log_emit_restores (region->entry_block, code_bb);
2756 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2757 edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2758 edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2759 redirect_edge_pred (fallthru_edge, join_bb);
2761 join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2762 join_bb->count = test_bb->count = transaction_bb->count;
2764 ei->probability = PROB_ALWAYS;
2765 et->probability = PROB_LIKELY;
2766 ef->probability = PROB_UNLIKELY;
2767 et->count = apply_probability (test_bb->count, et->probability);
2768 ef->count = apply_probability (test_bb->count, ef->probability);
2770 code_bb->count = et->count;
2771 code_bb->frequency = EDGE_FREQUENCY (et);
2773 transaction_bb = join_bb;
2776 // If we have an ABORT edge, create a test to perform the abort.
2777 if (abort_edge)
2779 basic_block test_bb = create_empty_bb (transaction_bb);
2780 if (current_loops && transaction_bb->loop_father)
2781 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2782 if (region->restart_block == region->entry_block)
2783 region->restart_block = test_bb;
2785 tree t1 = create_tmp_reg (tm_state_type, NULL);
2786 tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2787 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2788 tm_state, t2);
2789 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2790 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2792 t2 = build_int_cst (tm_state_type, 0);
2793 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2794 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2796 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2797 test_bb->frequency = transaction_bb->frequency;
2798 test_bb->count = transaction_bb->count;
2799 ei->probability = PROB_ALWAYS;
2801 // Not abort edge. If both are live, chose one at random as we'll
2802 // we'll be fixing that up below.
2803 redirect_edge_pred (fallthru_edge, test_bb);
2804 fallthru_edge->flags = EDGE_FALSE_VALUE;
2805 fallthru_edge->probability = PROB_VERY_LIKELY;
2806 fallthru_edge->count
2807 = apply_probability (test_bb->count, fallthru_edge->probability);
2809 // Abort/over edge.
2810 redirect_edge_pred (abort_edge, test_bb);
2811 abort_edge->flags = EDGE_TRUE_VALUE;
2812 abort_edge->probability = PROB_VERY_UNLIKELY;
2813 abort_edge->count
2814 = apply_probability (test_bb->count, abort_edge->probability);
2816 transaction_bb = test_bb;
2819 // If we have both instrumented and uninstrumented code paths, select one.
2820 if (inst_edge && uninst_edge)
2822 basic_block test_bb = create_empty_bb (transaction_bb);
2823 if (current_loops && transaction_bb->loop_father)
2824 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2825 if (region->restart_block == region->entry_block)
2826 region->restart_block = test_bb;
2828 tree t1 = create_tmp_reg (tm_state_type, NULL);
2829 tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2831 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2832 tm_state, t2);
2833 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2834 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2836 t2 = build_int_cst (tm_state_type, 0);
2837 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2838 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2840 // Create the edge into test_bb first, as we want to copy values
2841 // out of the fallthru edge.
2842 edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2843 e->probability = fallthru_edge->probability;
2844 test_bb->count = e->count = fallthru_edge->count;
2845 test_bb->frequency = EDGE_FREQUENCY (e);
2847 // Now update the edges to the inst/uninist implementations.
2848 // For now assume that the paths are equally likely. When using HTM,
2849 // we'll try the uninst path first and fallback to inst path if htm
2850 // buffers are exceeded. Without HTM we start with the inst path and
2851 // use the uninst path when falling back to serial mode.
2852 redirect_edge_pred (inst_edge, test_bb);
2853 inst_edge->flags = EDGE_FALSE_VALUE;
2854 inst_edge->probability = REG_BR_PROB_BASE / 2;
2855 inst_edge->count
2856 = apply_probability (test_bb->count, inst_edge->probability);
2858 redirect_edge_pred (uninst_edge, test_bb);
2859 uninst_edge->flags = EDGE_TRUE_VALUE;
2860 uninst_edge->probability = REG_BR_PROB_BASE / 2;
2861 uninst_edge->count
2862 = apply_probability (test_bb->count, uninst_edge->probability);
2865 // If we have no previous special cases, and we have PHIs at the beginning
2866 // of the atomic region, this means we have a loop at the beginning of the
2867 // atomic region that shares the first block. This can cause problems with
2868 // the transaction restart abnormal edges to be added in the tm_edges pass.
2869 // Solve this by adding a new empty block to receive the abnormal edges.
2870 if (region->restart_block == region->entry_block
2871 && phi_nodes (region->entry_block))
2873 basic_block empty_bb = create_empty_bb (transaction_bb);
2874 region->restart_block = empty_bb;
2875 if (current_loops && transaction_bb->loop_father)
2876 add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2878 redirect_edge_pred (fallthru_edge, empty_bb);
2879 make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2882 return NULL;
2885 /* Generate the temporary to be used for the return value of
2886 BUILT_IN_TM_START. */
2888 static void *
2889 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2891 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2892 region->tm_state =
2893 create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2895 // Reset the subcode, post optimizations. We'll fill this in
2896 // again as we process blocks.
2897 if (region->exit_blocks)
2899 unsigned int subcode
2900 = gimple_transaction_subcode (region->transaction_stmt);
2902 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2903 subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2904 | GTMA_MAY_ENTER_IRREVOCABLE
2905 | GTMA_HAS_NO_INSTRUMENTATION);
2906 else
2907 subcode &= GTMA_DECLARATION_MASK;
2908 gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2911 return NULL;
2914 // Propagate flags from inner transactions outwards.
2915 static void
2916 propagate_tm_flags_out (struct tm_region *region)
2918 if (region == NULL)
2919 return;
2920 propagate_tm_flags_out (region->inner);
2922 if (region->outer && region->outer->transaction_stmt)
2924 unsigned s = gimple_transaction_subcode (region->transaction_stmt);
2925 s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2926 | GTMA_MAY_ENTER_IRREVOCABLE);
2927 s |= gimple_transaction_subcode (region->outer->transaction_stmt);
2928 gimple_transaction_set_subcode (region->outer->transaction_stmt, s);
2931 propagate_tm_flags_out (region->next);
2934 /* Entry point to the MARK phase of TM expansion. Here we replace
2935 transactional memory statements with calls to builtins, and function
2936 calls with their transactional clones (if available). But we don't
2937 yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges. */
2939 static unsigned int
2940 execute_tm_mark (void)
2942 pending_edge_inserts_p = false;
2944 expand_regions (all_tm_regions, generate_tm_state, NULL,
2945 /*traverse_clones=*/true);
2947 tm_log_init ();
2949 vec<tm_region_p> bb_regions
2950 = get_bb_regions_instrumented (/*traverse_clones=*/true,
2951 /*include_uninstrumented_p=*/false);
2952 struct tm_region *r;
2953 unsigned i;
2955 // Expand memory operations into calls into the runtime.
2956 // This collects log entries as well.
2957 FOR_EACH_VEC_ELT (bb_regions, i, r)
2959 if (r != NULL)
2961 if (r->transaction_stmt)
2963 unsigned sub = gimple_transaction_subcode (r->transaction_stmt);
2965 /* If we're sure to go irrevocable, there won't be
2966 anything to expand, since the run-time will go
2967 irrevocable right away. */
2968 if (sub & GTMA_DOES_GO_IRREVOCABLE
2969 && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2970 continue;
2972 expand_block_tm (r, BASIC_BLOCK (i));
2976 bb_regions.release ();
2978 // Propagate flags from inner transactions outwards.
2979 propagate_tm_flags_out (all_tm_regions);
2981 // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
2982 expand_regions (all_tm_regions, expand_transaction, NULL,
2983 /*traverse_clones=*/false);
2985 tm_log_emit ();
2986 tm_log_delete ();
2988 if (pending_edge_inserts_p)
2989 gsi_commit_edge_inserts ();
2990 free_dominance_info (CDI_DOMINATORS);
2991 return 0;
2994 namespace {
2996 const pass_data pass_data_tm_mark =
2998 GIMPLE_PASS, /* type */
2999 "tmmark", /* name */
3000 OPTGROUP_NONE, /* optinfo_flags */
3001 false, /* has_gate */
3002 true, /* has_execute */
3003 TV_TRANS_MEM, /* tv_id */
3004 ( PROP_ssa | PROP_cfg ), /* properties_required */
3005 0, /* properties_provided */
3006 0, /* properties_destroyed */
3007 0, /* todo_flags_start */
3008 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3011 class pass_tm_mark : public gimple_opt_pass
3013 public:
3014 pass_tm_mark (gcc::context *ctxt)
3015 : gimple_opt_pass (pass_data_tm_mark, ctxt)
3018 /* opt_pass methods: */
3019 unsigned int execute () { return execute_tm_mark (); }
3021 }; // class pass_tm_mark
3023 } // anon namespace
3025 gimple_opt_pass *
3026 make_pass_tm_mark (gcc::context *ctxt)
3028 return new pass_tm_mark (ctxt);
3032 /* Create an abnormal edge from STMT at iter, splitting the block
3033 as necessary. Adjust *PNEXT as needed for the split block. */
3035 static inline void
3036 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3037 gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3039 basic_block bb = gimple_bb (stmt);
3040 if (!gsi_one_before_end_p (iter))
3042 edge e = split_block (bb, stmt);
3043 *pnext = gsi_start_bb (e->dest);
3045 make_edge (bb, dest_bb, EDGE_ABNORMAL);
3047 // Record the need for the edge for the benefit of the rtl passes.
3048 if (cfun->gimple_df->tm_restart == NULL)
3049 cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
3050 struct_ptr_eq, ggc_free);
3052 struct tm_restart_node dummy;
3053 dummy.stmt = stmt;
3054 dummy.label_or_list = gimple_block_label (dest_bb);
3056 void **slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
3057 struct tm_restart_node *n = (struct tm_restart_node *) *slot;
3058 if (n == NULL)
3060 n = ggc_alloc_tm_restart_node ();
3061 *n = dummy;
3063 else
3065 tree old = n->label_or_list;
3066 if (TREE_CODE (old) == LABEL_DECL)
3067 old = tree_cons (NULL, old, NULL);
3068 n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3072 /* Split block BB as necessary for every builtin function we added, and
3073 wire up the abnormal back edges implied by the transaction restart. */
3075 static void
3076 expand_block_edges (struct tm_region *const region, basic_block bb)
3078 gimple_stmt_iterator gsi, next_gsi;
3080 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3082 gimple stmt = gsi_stmt (gsi);
3084 next_gsi = gsi;
3085 gsi_next (&next_gsi);
3087 // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3088 if (gimple_code (stmt) != GIMPLE_CALL
3089 || (gimple_call_flags (stmt) & ECF_TM_BUILTIN) == 0)
3090 continue;
3092 if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_TM_ABORT)
3094 // If we have a ``_transaction_cancel [[outer]]'', there is only
3095 // one abnormal edge: to the transaction marked OUTER.
3096 // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3097 // constant argument, which we can examine here. Users invoking
3098 // TM_ABORT directly get what they deserve.
3099 tree arg = gimple_call_arg (stmt, 0);
3100 if (TREE_CODE (arg) == INTEGER_CST
3101 && (TREE_INT_CST_LOW (arg) & AR_OUTERABORT) != 0
3102 && !decl_is_tm_clone (current_function_decl))
3104 // Find the GTMA_IS_OUTER transaction.
3105 for (struct tm_region *o = region; o; o = o->outer)
3106 if (o->original_transaction_was_outer)
3108 split_bb_make_tm_edge (stmt, o->restart_block,
3109 gsi, &next_gsi);
3110 break;
3113 // Otherwise, the front-end should have semantically checked
3114 // outer aborts, but in either case the target region is not
3115 // within this function.
3116 continue;
3119 // Non-outer, TM aborts have an abnormal edge to the inner-most
3120 // transaction, the one being aborted;
3121 split_bb_make_tm_edge (stmt, region->restart_block, gsi, &next_gsi);
3124 // All TM builtins have an abnormal edge to the outer-most transaction.
3125 // We never restart inner transactions. For tm clones, we know a-priori
3126 // that the outer-most transaction is outside the function.
3127 if (decl_is_tm_clone (current_function_decl))
3128 continue;
3130 if (cfun->gimple_df->tm_restart == NULL)
3131 cfun->gimple_df->tm_restart
3132 = htab_create_ggc (31, struct_ptr_hash, struct_ptr_eq, ggc_free);
3134 // All TM builtins have an abnormal edge to the outer-most transaction.
3135 // We never restart inner transactions.
3136 for (struct tm_region *o = region; o; o = o->outer)
3137 if (!o->outer)
3139 split_bb_make_tm_edge (stmt, o->restart_block, gsi, &next_gsi);
3140 break;
3143 // Delete any tail-call annotation that may have been added.
3144 // The tail-call pass may have mis-identified the commit as being
3145 // a candidate because we had not yet added this restart edge.
3146 gimple_call_set_tail (stmt, false);
3150 /* Entry point to the final expansion of transactional nodes. */
3152 static unsigned int
3153 execute_tm_edges (void)
3155 vec<tm_region_p> bb_regions
3156 = get_bb_regions_instrumented (/*traverse_clones=*/false,
3157 /*include_uninstrumented_p=*/true);
3158 struct tm_region *r;
3159 unsigned i;
3161 FOR_EACH_VEC_ELT (bb_regions, i, r)
3162 if (r != NULL)
3163 expand_block_edges (r, BASIC_BLOCK (i));
3165 bb_regions.release ();
3167 /* We've got to release the dominance info now, to indicate that it
3168 must be rebuilt completely. Otherwise we'll crash trying to update
3169 the SSA web in the TODO section following this pass. */
3170 free_dominance_info (CDI_DOMINATORS);
3171 bitmap_obstack_release (&tm_obstack);
3172 all_tm_regions = NULL;
3174 return 0;
3177 namespace {
3179 const pass_data pass_data_tm_edges =
3181 GIMPLE_PASS, /* type */
3182 "tmedge", /* name */
3183 OPTGROUP_NONE, /* optinfo_flags */
3184 false, /* has_gate */
3185 true, /* has_execute */
3186 TV_TRANS_MEM, /* tv_id */
3187 ( PROP_ssa | PROP_cfg ), /* properties_required */
3188 0, /* properties_provided */
3189 0, /* properties_destroyed */
3190 0, /* todo_flags_start */
3191 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3194 class pass_tm_edges : public gimple_opt_pass
3196 public:
3197 pass_tm_edges (gcc::context *ctxt)
3198 : gimple_opt_pass (pass_data_tm_edges, ctxt)
3201 /* opt_pass methods: */
3202 unsigned int execute () { return execute_tm_edges (); }
3204 }; // class pass_tm_edges
3206 } // anon namespace
3208 gimple_opt_pass *
3209 make_pass_tm_edges (gcc::context *ctxt)
3211 return new pass_tm_edges (ctxt);
3214 /* Helper function for expand_regions. Expand REGION and recurse to
3215 the inner region. Call CALLBACK on each region. CALLBACK returns
3216 NULL to continue the traversal, otherwise a non-null value which
3217 this function will return as well. TRAVERSE_CLONES is true if we
3218 should traverse transactional clones. */
3220 static void *
3221 expand_regions_1 (struct tm_region *region,
3222 void *(*callback)(struct tm_region *, void *),
3223 void *data,
3224 bool traverse_clones)
3226 void *retval = NULL;
3227 if (region->exit_blocks
3228 || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3230 retval = callback (region, data);
3231 if (retval)
3232 return retval;
3234 if (region->inner)
3236 retval = expand_regions (region->inner, callback, data, traverse_clones);
3237 if (retval)
3238 return retval;
3240 return retval;
3243 /* Traverse the regions enclosed and including REGION. Execute
3244 CALLBACK for each region, passing DATA. CALLBACK returns NULL to
3245 continue the traversal, otherwise a non-null value which this
3246 function will return as well. TRAVERSE_CLONES is true if we should
3247 traverse transactional clones. */
3249 static void *
3250 expand_regions (struct tm_region *region,
3251 void *(*callback)(struct tm_region *, void *),
3252 void *data,
3253 bool traverse_clones)
3255 void *retval = NULL;
3256 while (region)
3258 retval = expand_regions_1 (region, callback, data, traverse_clones);
3259 if (retval)
3260 return retval;
3261 region = region->next;
3263 return retval;
3267 /* A unique TM memory operation. */
3268 typedef struct tm_memop
3270 /* Unique ID that all memory operations to the same location have. */
3271 unsigned int value_id;
3272 /* Address of load/store. */
3273 tree addr;
3274 } *tm_memop_t;
3276 /* TM memory operation hashtable helpers. */
3278 struct tm_memop_hasher : typed_free_remove <tm_memop>
3280 typedef tm_memop value_type;
3281 typedef tm_memop compare_type;
3282 static inline hashval_t hash (const value_type *);
3283 static inline bool equal (const value_type *, const compare_type *);
3286 /* Htab support. Return a hash value for a `tm_memop'. */
3287 inline hashval_t
3288 tm_memop_hasher::hash (const value_type *mem)
3290 tree addr = mem->addr;
3291 /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3292 actually done with operand_equal_p (see tm_memop_eq). */
3293 if (TREE_CODE (addr) == ADDR_EXPR)
3294 addr = TREE_OPERAND (addr, 0);
3295 return iterative_hash_expr (addr, 0);
3298 /* Htab support. Return true if two tm_memop's are the same. */
3299 inline bool
3300 tm_memop_hasher::equal (const value_type *mem1, const compare_type *mem2)
3302 return operand_equal_p (mem1->addr, mem2->addr, 0);
3305 /* Sets for solving data flow equations in the memory optimization pass. */
3306 struct tm_memopt_bitmaps
3308 /* Stores available to this BB upon entry. Basically, stores that
3309 dominate this BB. */
3310 bitmap store_avail_in;
3311 /* Stores available at the end of this BB. */
3312 bitmap store_avail_out;
3313 bitmap store_antic_in;
3314 bitmap store_antic_out;
3315 /* Reads available to this BB upon entry. Basically, reads that
3316 dominate this BB. */
3317 bitmap read_avail_in;
3318 /* Reads available at the end of this BB. */
3319 bitmap read_avail_out;
3320 /* Reads performed in this BB. */
3321 bitmap read_local;
3322 /* Writes performed in this BB. */
3323 bitmap store_local;
3325 /* Temporary storage for pass. */
3326 /* Is the current BB in the worklist? */
3327 bool avail_in_worklist_p;
3328 /* Have we visited this BB? */
3329 bool visited_p;
3332 static bitmap_obstack tm_memopt_obstack;
3334 /* Unique counter for TM loads and stores. Loads and stores of the
3335 same address get the same ID. */
3336 static unsigned int tm_memopt_value_id;
3337 static hash_table <tm_memop_hasher> tm_memopt_value_numbers;
3339 #define STORE_AVAIL_IN(BB) \
3340 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3341 #define STORE_AVAIL_OUT(BB) \
3342 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3343 #define STORE_ANTIC_IN(BB) \
3344 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3345 #define STORE_ANTIC_OUT(BB) \
3346 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3347 #define READ_AVAIL_IN(BB) \
3348 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3349 #define READ_AVAIL_OUT(BB) \
3350 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3351 #define READ_LOCAL(BB) \
3352 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3353 #define STORE_LOCAL(BB) \
3354 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3355 #define AVAIL_IN_WORKLIST_P(BB) \
3356 ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3357 #define BB_VISITED_P(BB) \
3358 ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3360 /* Given a TM load/store in STMT, return the value number for the address
3361 it accesses. */
3363 static unsigned int
3364 tm_memopt_value_number (gimple stmt, enum insert_option op)
3366 struct tm_memop tmpmem, *mem;
3367 tm_memop **slot;
3369 gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3370 tmpmem.addr = gimple_call_arg (stmt, 0);
3371 slot = tm_memopt_value_numbers.find_slot (&tmpmem, op);
3372 if (*slot)
3373 mem = *slot;
3374 else if (op == INSERT)
3376 mem = XNEW (struct tm_memop);
3377 *slot = mem;
3378 mem->value_id = tm_memopt_value_id++;
3379 mem->addr = tmpmem.addr;
3381 else
3382 gcc_unreachable ();
3383 return mem->value_id;
3386 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL. */
3388 static void
3389 tm_memopt_accumulate_memops (basic_block bb)
3391 gimple_stmt_iterator gsi;
3393 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3395 gimple stmt = gsi_stmt (gsi);
3396 bitmap bits;
3397 unsigned int loc;
3399 if (is_tm_store (stmt))
3400 bits = STORE_LOCAL (bb);
3401 else if (is_tm_load (stmt))
3402 bits = READ_LOCAL (bb);
3403 else
3404 continue;
3406 loc = tm_memopt_value_number (stmt, INSERT);
3407 bitmap_set_bit (bits, loc);
3408 if (dump_file)
3410 fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3411 is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3412 gimple_bb (stmt)->index);
3413 print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3414 fprintf (dump_file, "\n");
3419 /* Prettily dump one of the memopt sets. BITS is the bitmap to dump. */
3421 static void
3422 dump_tm_memopt_set (const char *set_name, bitmap bits)
3424 unsigned i;
3425 bitmap_iterator bi;
3426 const char *comma = "";
3428 fprintf (dump_file, "TM memopt: %s: [", set_name);
3429 EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3431 hash_table <tm_memop_hasher>::iterator hi;
3432 struct tm_memop *mem = NULL;
3434 /* Yeah, yeah, yeah. Whatever. This is just for debugging. */
3435 FOR_EACH_HASH_TABLE_ELEMENT (tm_memopt_value_numbers, mem, tm_memop_t, hi)
3436 if (mem->value_id == i)
3437 break;
3438 gcc_assert (mem->value_id == i);
3439 fprintf (dump_file, "%s", comma);
3440 comma = ", ";
3441 print_generic_expr (dump_file, mem->addr, 0);
3443 fprintf (dump_file, "]\n");
3446 /* Prettily dump all of the memopt sets in BLOCKS. */
3448 static void
3449 dump_tm_memopt_sets (vec<basic_block> blocks)
3451 size_t i;
3452 basic_block bb;
3454 for (i = 0; blocks.iterate (i, &bb); ++i)
3456 fprintf (dump_file, "------------BB %d---------\n", bb->index);
3457 dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3458 dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3459 dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3460 dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3461 dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3462 dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3466 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB. */
3468 static void
3469 tm_memopt_compute_avin (basic_block bb)
3471 edge e;
3472 unsigned ix;
3474 /* Seed with the AVOUT of any predecessor. */
3475 for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3477 e = EDGE_PRED (bb, ix);
3478 /* Make sure we have already visited this BB, and is thus
3479 initialized.
3481 If e->src->aux is NULL, this predecessor is actually on an
3482 enclosing transaction. We only care about the current
3483 transaction, so ignore it. */
3484 if (e->src->aux && BB_VISITED_P (e->src))
3486 bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3487 bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3488 break;
3492 for (; ix < EDGE_COUNT (bb->preds); ix++)
3494 e = EDGE_PRED (bb, ix);
3495 if (e->src->aux && BB_VISITED_P (e->src))
3497 bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3498 bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3502 BB_VISITED_P (bb) = true;
3505 /* Compute the STORE_ANTIC_IN for the basic block BB. */
3507 static void
3508 tm_memopt_compute_antin (basic_block bb)
3510 edge e;
3511 unsigned ix;
3513 /* Seed with the ANTIC_OUT of any successor. */
3514 for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3516 e = EDGE_SUCC (bb, ix);
3517 /* Make sure we have already visited this BB, and is thus
3518 initialized. */
3519 if (BB_VISITED_P (e->dest))
3521 bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3522 break;
3526 for (; ix < EDGE_COUNT (bb->succs); ix++)
3528 e = EDGE_SUCC (bb, ix);
3529 if (BB_VISITED_P (e->dest))
3530 bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3533 BB_VISITED_P (bb) = true;
3536 /* Compute the AVAIL sets for every basic block in BLOCKS.
3538 We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3540 AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3541 AVAIL_IN[bb] = intersect (AVAIL_OUT[predecessors])
3543 This is basically what we do in lcm's compute_available(), but here
3544 we calculate two sets of sets (one for STOREs and one for READs),
3545 and we work on a region instead of the entire CFG.
3547 REGION is the TM region.
3548 BLOCKS are the basic blocks in the region. */
3550 static void
3551 tm_memopt_compute_available (struct tm_region *region,
3552 vec<basic_block> blocks)
3554 edge e;
3555 basic_block *worklist, *qin, *qout, *qend, bb;
3556 unsigned int qlen, i;
3557 edge_iterator ei;
3558 bool changed;
3560 /* Allocate a worklist array/queue. Entries are only added to the
3561 list if they were not already on the list. So the size is
3562 bounded by the number of basic blocks in the region. */
3563 qlen = blocks.length () - 1;
3564 qin = qout = worklist =
3565 XNEWVEC (basic_block, qlen);
3567 /* Put every block in the region on the worklist. */
3568 for (i = 0; blocks.iterate (i, &bb); ++i)
3570 /* Seed AVAIL_OUT with the LOCAL set. */
3571 bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3572 bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3574 AVAIL_IN_WORKLIST_P (bb) = true;
3575 /* No need to insert the entry block, since it has an AVIN of
3576 null, and an AVOUT that has already been seeded in. */
3577 if (bb != region->entry_block)
3578 *qin++ = bb;
3581 /* The entry block has been initialized with the local sets. */
3582 BB_VISITED_P (region->entry_block) = true;
3584 qin = worklist;
3585 qend = &worklist[qlen];
3587 /* Iterate until the worklist is empty. */
3588 while (qlen)
3590 /* Take the first entry off the worklist. */
3591 bb = *qout++;
3592 qlen--;
3594 if (qout >= qend)
3595 qout = worklist;
3597 /* This block can be added to the worklist again if necessary. */
3598 AVAIL_IN_WORKLIST_P (bb) = false;
3599 tm_memopt_compute_avin (bb);
3601 /* Note: We do not add the LOCAL sets here because we already
3602 seeded the AVAIL_OUT sets with them. */
3603 changed = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3604 changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3605 if (changed
3606 && (region->exit_blocks == NULL
3607 || !bitmap_bit_p (region->exit_blocks, bb->index)))
3608 /* If the out state of this block changed, then we need to add
3609 its successors to the worklist if they are not already in. */
3610 FOR_EACH_EDGE (e, ei, bb->succs)
3611 if (!AVAIL_IN_WORKLIST_P (e->dest) && e->dest != EXIT_BLOCK_PTR)
3613 *qin++ = e->dest;
3614 AVAIL_IN_WORKLIST_P (e->dest) = true;
3615 qlen++;
3617 if (qin >= qend)
3618 qin = worklist;
3622 free (worklist);
3624 if (dump_file)
3625 dump_tm_memopt_sets (blocks);
3628 /* Compute ANTIC sets for every basic block in BLOCKS.
3630 We compute STORE_ANTIC_OUT as follows:
3632 STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3633 STORE_ANTIC_IN[bb] = intersect(STORE_ANTIC_OUT[successors])
3635 REGION is the TM region.
3636 BLOCKS are the basic blocks in the region. */
3638 static void
3639 tm_memopt_compute_antic (struct tm_region *region,
3640 vec<basic_block> blocks)
3642 edge e;
3643 basic_block *worklist, *qin, *qout, *qend, bb;
3644 unsigned int qlen;
3645 int i;
3646 edge_iterator ei;
3648 /* Allocate a worklist array/queue. Entries are only added to the
3649 list if they were not already on the list. So the size is
3650 bounded by the number of basic blocks in the region. */
3651 qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3653 for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3655 bb = blocks[i];
3657 /* Seed ANTIC_OUT with the LOCAL set. */
3658 bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3660 /* Put every block in the region on the worklist. */
3661 AVAIL_IN_WORKLIST_P (bb) = true;
3662 /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3663 and their ANTIC_OUT has already been seeded in. */
3664 if (region->exit_blocks
3665 && !bitmap_bit_p (region->exit_blocks, bb->index))
3667 qlen++;
3668 *qin++ = bb;
3672 /* The exit blocks have been initialized with the local sets. */
3673 if (region->exit_blocks)
3675 unsigned int i;
3676 bitmap_iterator bi;
3677 EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3678 BB_VISITED_P (BASIC_BLOCK (i)) = true;
3681 qin = worklist;
3682 qend = &worklist[qlen];
3684 /* Iterate until the worklist is empty. */
3685 while (qlen)
3687 /* Take the first entry off the worklist. */
3688 bb = *qout++;
3689 qlen--;
3691 if (qout >= qend)
3692 qout = worklist;
3694 /* This block can be added to the worklist again if necessary. */
3695 AVAIL_IN_WORKLIST_P (bb) = false;
3696 tm_memopt_compute_antin (bb);
3698 /* Note: We do not add the LOCAL sets here because we already
3699 seeded the ANTIC_OUT sets with them. */
3700 if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3701 && bb != region->entry_block)
3702 /* If the out state of this block changed, then we need to add
3703 its predecessors to the worklist if they are not already in. */
3704 FOR_EACH_EDGE (e, ei, bb->preds)
3705 if (!AVAIL_IN_WORKLIST_P (e->src))
3707 *qin++ = e->src;
3708 AVAIL_IN_WORKLIST_P (e->src) = true;
3709 qlen++;
3711 if (qin >= qend)
3712 qin = worklist;
3716 free (worklist);
3718 if (dump_file)
3719 dump_tm_memopt_sets (blocks);
3722 /* Offsets of load variants from TM_LOAD. For example,
3723 BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3724 See gtm-builtins.def. */
3725 #define TRANSFORM_RAR 1
3726 #define TRANSFORM_RAW 2
3727 #define TRANSFORM_RFW 3
3728 /* Offsets of store variants from TM_STORE. */
3729 #define TRANSFORM_WAR 1
3730 #define TRANSFORM_WAW 2
3732 /* Inform about a load/store optimization. */
3734 static void
3735 dump_tm_memopt_transform (gimple stmt)
3737 if (dump_file)
3739 fprintf (dump_file, "TM memopt: transforming: ");
3740 print_gimple_stmt (dump_file, stmt, 0, 0);
3741 fprintf (dump_file, "\n");
3745 /* Perform a read/write optimization. Replaces the TM builtin in STMT
3746 by a builtin that is OFFSET entries down in the builtins table in
3747 gtm-builtins.def. */
3749 static void
3750 tm_memopt_transform_stmt (unsigned int offset,
3751 gimple stmt,
3752 gimple_stmt_iterator *gsi)
3754 tree fn = gimple_call_fn (stmt);
3755 gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3756 TREE_OPERAND (fn, 0)
3757 = builtin_decl_explicit ((enum built_in_function)
3758 (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3759 + offset));
3760 gimple_call_set_fn (stmt, fn);
3761 gsi_replace (gsi, stmt, true);
3762 dump_tm_memopt_transform (stmt);
3765 /* Perform the actual TM memory optimization transformations in the
3766 basic blocks in BLOCKS. */
3768 static void
3769 tm_memopt_transform_blocks (vec<basic_block> blocks)
3771 size_t i;
3772 basic_block bb;
3773 gimple_stmt_iterator gsi;
3775 for (i = 0; blocks.iterate (i, &bb); ++i)
3777 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3779 gimple stmt = gsi_stmt (gsi);
3780 bitmap read_avail = READ_AVAIL_IN (bb);
3781 bitmap store_avail = STORE_AVAIL_IN (bb);
3782 bitmap store_antic = STORE_ANTIC_OUT (bb);
3783 unsigned int loc;
3785 if (is_tm_simple_load (stmt))
3787 loc = tm_memopt_value_number (stmt, NO_INSERT);
3788 if (store_avail && bitmap_bit_p (store_avail, loc))
3789 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3790 else if (store_antic && bitmap_bit_p (store_antic, loc))
3792 tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3793 bitmap_set_bit (store_avail, loc);
3795 else if (read_avail && bitmap_bit_p (read_avail, loc))
3796 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3797 else
3798 bitmap_set_bit (read_avail, loc);
3800 else if (is_tm_simple_store (stmt))
3802 loc = tm_memopt_value_number (stmt, NO_INSERT);
3803 if (store_avail && bitmap_bit_p (store_avail, loc))
3804 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3805 else
3807 if (read_avail && bitmap_bit_p (read_avail, loc))
3808 tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3809 bitmap_set_bit (store_avail, loc);
3816 /* Return a new set of bitmaps for a BB. */
3818 static struct tm_memopt_bitmaps *
3819 tm_memopt_init_sets (void)
3821 struct tm_memopt_bitmaps *b
3822 = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3823 b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3824 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3825 b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3826 b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3827 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3828 b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3829 b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3830 b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3831 b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3832 return b;
3835 /* Free sets computed for each BB. */
3837 static void
3838 tm_memopt_free_sets (vec<basic_block> blocks)
3840 size_t i;
3841 basic_block bb;
3843 for (i = 0; blocks.iterate (i, &bb); ++i)
3844 bb->aux = NULL;
3847 /* Clear the visited bit for every basic block in BLOCKS. */
3849 static void
3850 tm_memopt_clear_visited (vec<basic_block> blocks)
3852 size_t i;
3853 basic_block bb;
3855 for (i = 0; blocks.iterate (i, &bb); ++i)
3856 BB_VISITED_P (bb) = false;
3859 /* Replace TM load/stores with hints for the runtime. We handle
3860 things like read-after-write, write-after-read, read-after-read,
3861 read-for-write, etc. */
3863 static unsigned int
3864 execute_tm_memopt (void)
3866 struct tm_region *region;
3867 vec<basic_block> bbs;
3869 tm_memopt_value_id = 0;
3870 tm_memopt_value_numbers.create (10);
3872 for (region = all_tm_regions; region; region = region->next)
3874 /* All the TM stores/loads in the current region. */
3875 size_t i;
3876 basic_block bb;
3878 bitmap_obstack_initialize (&tm_memopt_obstack);
3880 /* Save all BBs for the current region. */
3881 bbs = get_tm_region_blocks (region->entry_block,
3882 region->exit_blocks,
3883 region->irr_blocks,
3884 NULL,
3885 false);
3887 /* Collect all the memory operations. */
3888 for (i = 0; bbs.iterate (i, &bb); ++i)
3890 bb->aux = tm_memopt_init_sets ();
3891 tm_memopt_accumulate_memops (bb);
3894 /* Solve data flow equations and transform each block accordingly. */
3895 tm_memopt_clear_visited (bbs);
3896 tm_memopt_compute_available (region, bbs);
3897 tm_memopt_clear_visited (bbs);
3898 tm_memopt_compute_antic (region, bbs);
3899 tm_memopt_transform_blocks (bbs);
3901 tm_memopt_free_sets (bbs);
3902 bbs.release ();
3903 bitmap_obstack_release (&tm_memopt_obstack);
3904 tm_memopt_value_numbers.empty ();
3907 tm_memopt_value_numbers.dispose ();
3908 return 0;
3911 static bool
3912 gate_tm_memopt (void)
3914 return flag_tm && optimize > 0;
3917 namespace {
3919 const pass_data pass_data_tm_memopt =
3921 GIMPLE_PASS, /* type */
3922 "tmmemopt", /* name */
3923 OPTGROUP_NONE, /* optinfo_flags */
3924 true, /* has_gate */
3925 true, /* has_execute */
3926 TV_TRANS_MEM, /* tv_id */
3927 ( PROP_ssa | PROP_cfg ), /* properties_required */
3928 0, /* properties_provided */
3929 0, /* properties_destroyed */
3930 0, /* todo_flags_start */
3931 0, /* todo_flags_finish */
3934 class pass_tm_memopt : public gimple_opt_pass
3936 public:
3937 pass_tm_memopt (gcc::context *ctxt)
3938 : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3941 /* opt_pass methods: */
3942 bool gate () { return gate_tm_memopt (); }
3943 unsigned int execute () { return execute_tm_memopt (); }
3945 }; // class pass_tm_memopt
3947 } // anon namespace
3949 gimple_opt_pass *
3950 make_pass_tm_memopt (gcc::context *ctxt)
3952 return new pass_tm_memopt (ctxt);
3956 /* Interprocedual analysis for the creation of transactional clones.
3957 The aim of this pass is to find which functions are referenced in
3958 a non-irrevocable transaction context, and for those over which
3959 we have control (or user directive), create a version of the
3960 function which uses only the transactional interface to reference
3961 protected memories. This analysis proceeds in several steps:
3963 (1) Collect the set of all possible transactional clones:
3965 (a) For all local public functions marked tm_callable, push
3966 it onto the tm_callee queue.
3968 (b) For all local functions, scan for calls in transaction blocks.
3969 Push the caller and callee onto the tm_caller and tm_callee
3970 queues. Count the number of callers for each callee.
3972 (c) For each local function on the callee list, assume we will
3973 create a transactional clone. Push *all* calls onto the
3974 callee queues; count the number of clone callers separately
3975 to the number of original callers.
3977 (2) Propagate irrevocable status up the dominator tree:
3979 (a) Any external function on the callee list that is not marked
3980 tm_callable is irrevocable. Push all callers of such onto
3981 a worklist.
3983 (b) For each function on the worklist, mark each block that
3984 contains an irrevocable call. Use the AND operator to
3985 propagate that mark up the dominator tree.
3987 (c) If we reach the entry block for a possible transactional
3988 clone, then the transactional clone is irrevocable, and
3989 we should not create the clone after all. Push all
3990 callers onto the worklist.
3992 (d) Place tm_irrevocable calls at the beginning of the relevant
3993 blocks. Special case here is the entry block for the entire
3994 transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
3995 the library to begin the region in serial mode. Decrement
3996 the call count for all callees in the irrevocable region.
3998 (3) Create the transactional clones:
4000 Any tm_callee that still has a non-zero call count is cloned.
4003 /* This structure is stored in the AUX field of each cgraph_node. */
4004 struct tm_ipa_cg_data
4006 /* The clone of the function that got created. */
4007 struct cgraph_node *clone;
4009 /* The tm regions in the normal function. */
4010 struct tm_region *all_tm_regions;
4012 /* The blocks of the normal/clone functions that contain irrevocable
4013 calls, or blocks that are post-dominated by irrevocable calls. */
4014 bitmap irrevocable_blocks_normal;
4015 bitmap irrevocable_blocks_clone;
4017 /* The blocks of the normal function that are involved in transactions. */
4018 bitmap transaction_blocks_normal;
4020 /* The number of callers to the transactional clone of this function
4021 from normal and transactional clones respectively. */
4022 unsigned tm_callers_normal;
4023 unsigned tm_callers_clone;
4025 /* True if all calls to this function's transactional clone
4026 are irrevocable. Also automatically true if the function
4027 has no transactional clone. */
4028 bool is_irrevocable;
4030 /* Flags indicating the presence of this function in various queues. */
4031 bool in_callee_queue;
4032 bool in_worklist;
4034 /* Flags indicating the kind of scan desired while in the worklist. */
4035 bool want_irr_scan_normal;
4038 typedef vec<cgraph_node_ptr> cgraph_node_queue;
4040 /* Return the ipa data associated with NODE, allocating zeroed memory
4041 if necessary. TRAVERSE_ALIASES is true if we must traverse aliases
4042 and set *NODE accordingly. */
4044 static struct tm_ipa_cg_data *
4045 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4047 struct tm_ipa_cg_data *d;
4049 if (traverse_aliases && (*node)->alias)
4050 *node = cgraph_alias_target (*node);
4052 d = (struct tm_ipa_cg_data *) (*node)->aux;
4054 if (d == NULL)
4056 d = (struct tm_ipa_cg_data *)
4057 obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4058 (*node)->aux = (void *) d;
4059 memset (d, 0, sizeof (*d));
4062 return d;
4065 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4066 it is already present. */
4068 static void
4069 maybe_push_queue (struct cgraph_node *node,
4070 cgraph_node_queue *queue_p, bool *in_queue_p)
4072 if (!*in_queue_p)
4074 *in_queue_p = true;
4075 queue_p->safe_push (node);
4079 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4080 code path. QUEUE are the basic blocks inside the transaction
4081 represented in REGION.
4083 Later in split_code_paths() we will add the conditional to choose
4084 between the two alternatives. */
4086 static void
4087 ipa_uninstrument_transaction (struct tm_region *region,
4088 vec<basic_block> queue)
4090 gimple transaction = region->transaction_stmt;
4091 basic_block transaction_bb = gimple_bb (transaction);
4092 int n = queue.length ();
4093 basic_block *new_bbs = XNEWVEC (basic_block, n);
4095 copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4096 true);
4097 edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4098 add_phi_args_after_copy (new_bbs, n, e);
4100 // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4101 // a) EDGE_FALLTHRU into the transaction
4102 // b) EDGE_TM_ABORT out of the transaction
4103 // c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4105 free (new_bbs);
4108 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4109 Queue all callees within block BB. */
4111 static void
4112 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4113 basic_block bb, bool for_clone)
4115 gimple_stmt_iterator gsi;
4117 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4119 gimple stmt = gsi_stmt (gsi);
4120 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4122 tree fndecl = gimple_call_fndecl (stmt);
4123 if (fndecl)
4125 struct tm_ipa_cg_data *d;
4126 unsigned *pcallers;
4127 struct cgraph_node *node;
4129 if (is_tm_ending_fndecl (fndecl))
4130 continue;
4131 if (find_tm_replacement_function (fndecl))
4132 continue;
4134 node = cgraph_get_node (fndecl);
4135 gcc_assert (node != NULL);
4136 d = get_cg_data (&node, true);
4138 pcallers = (for_clone ? &d->tm_callers_clone
4139 : &d->tm_callers_normal);
4140 *pcallers += 1;
4142 maybe_push_queue (node, callees_p, &d->in_callee_queue);
4148 /* Scan all calls in NODE that are within a transaction region,
4149 and push the resulting nodes into the callee queue. */
4151 static void
4152 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4153 cgraph_node_queue *callees_p)
4155 struct tm_region *r;
4157 d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4158 d->all_tm_regions = all_tm_regions;
4160 for (r = all_tm_regions; r; r = r->next)
4162 vec<basic_block> bbs;
4163 basic_block bb;
4164 unsigned i;
4166 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4167 d->transaction_blocks_normal, false);
4169 // Generate the uninstrumented code path for this transaction.
4170 ipa_uninstrument_transaction (r, bbs);
4172 FOR_EACH_VEC_ELT (bbs, i, bb)
4173 ipa_tm_scan_calls_block (callees_p, bb, false);
4175 bbs.release ();
4178 // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4179 // copying them, rather than forcing us to do this externally.
4180 rebuild_cgraph_edges ();
4182 // ??? In ipa_uninstrument_transaction we don't try to update dominators
4183 // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4184 // Instead, just release dominators here so update_ssa recomputes them.
4185 free_dominance_info (CDI_DOMINATORS);
4187 // When building the uninstrumented code path, copy_bbs will have invoked
4188 // create_new_def_for starting an "ssa update context". There is only one
4189 // instance of this context, so resolve ssa updates before moving on to
4190 // the next function.
4191 update_ssa (TODO_update_ssa);
4194 /* Scan all calls in NODE as if this is the transactional clone,
4195 and push the destinations into the callee queue. */
4197 static void
4198 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4199 cgraph_node_queue *callees_p)
4201 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
4202 basic_block bb;
4204 FOR_EACH_BB_FN (bb, fn)
4205 ipa_tm_scan_calls_block (callees_p, bb, true);
4208 /* The function NODE has been detected to be irrevocable. Push all
4209 of its callers onto WORKLIST for the purpose of re-scanning them. */
4211 static void
4212 ipa_tm_note_irrevocable (struct cgraph_node *node,
4213 cgraph_node_queue *worklist_p)
4215 struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4216 struct cgraph_edge *e;
4218 d->is_irrevocable = true;
4220 for (e = node->callers; e ; e = e->next_caller)
4222 basic_block bb;
4223 struct cgraph_node *caller;
4225 /* Don't examine recursive calls. */
4226 if (e->caller == node)
4227 continue;
4228 /* Even if we think we can go irrevocable, believe the user
4229 above all. */
4230 if (is_tm_safe_or_pure (e->caller->decl))
4231 continue;
4233 caller = e->caller;
4234 d = get_cg_data (&caller, true);
4236 /* Check if the callee is in a transactional region. If so,
4237 schedule the function for normal re-scan as well. */
4238 bb = gimple_bb (e->call_stmt);
4239 gcc_assert (bb != NULL);
4240 if (d->transaction_blocks_normal
4241 && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4242 d->want_irr_scan_normal = true;
4244 maybe_push_queue (caller, worklist_p, &d->in_worklist);
4248 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4249 within the block is irrevocable. */
4251 static bool
4252 ipa_tm_scan_irr_block (basic_block bb)
4254 gimple_stmt_iterator gsi;
4255 tree fn;
4257 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4259 gimple stmt = gsi_stmt (gsi);
4260 switch (gimple_code (stmt))
4262 case GIMPLE_ASSIGN:
4263 if (gimple_assign_single_p (stmt))
4265 tree lhs = gimple_assign_lhs (stmt);
4266 tree rhs = gimple_assign_rhs1 (stmt);
4267 if (volatile_var_p (lhs) || volatile_var_p (rhs))
4268 return true;
4270 break;
4272 case GIMPLE_CALL:
4274 tree lhs = gimple_call_lhs (stmt);
4275 if (lhs && volatile_var_p (lhs))
4276 return true;
4278 if (is_tm_pure_call (stmt))
4279 break;
4281 fn = gimple_call_fn (stmt);
4283 /* Functions with the attribute are by definition irrevocable. */
4284 if (is_tm_irrevocable (fn))
4285 return true;
4287 /* For direct function calls, go ahead and check for replacement
4288 functions, or transitive irrevocable functions. For indirect
4289 functions, we'll ask the runtime. */
4290 if (TREE_CODE (fn) == ADDR_EXPR)
4292 struct tm_ipa_cg_data *d;
4293 struct cgraph_node *node;
4295 fn = TREE_OPERAND (fn, 0);
4296 if (is_tm_ending_fndecl (fn))
4297 break;
4298 if (find_tm_replacement_function (fn))
4299 break;
4301 node = cgraph_get_node (fn);
4302 d = get_cg_data (&node, true);
4304 /* Return true if irrevocable, but above all, believe
4305 the user. */
4306 if (d->is_irrevocable
4307 && !is_tm_safe_or_pure (fn))
4308 return true;
4310 break;
4313 case GIMPLE_ASM:
4314 /* ??? The Approved Method of indicating that an inline
4315 assembly statement is not relevant to the transaction
4316 is to wrap it in a __tm_waiver block. This is not
4317 yet implemented, so we can't check for it. */
4318 if (is_tm_safe (current_function_decl))
4320 tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4321 SET_EXPR_LOCATION (t, gimple_location (stmt));
4322 error ("%Kasm not allowed in %<transaction_safe%> function", t);
4324 return true;
4326 default:
4327 break;
4331 return false;
4334 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4335 for new irrevocable blocks, marking them in NEW_IRR. Don't bother
4336 scanning past OLD_IRR or EXIT_BLOCKS. */
4338 static bool
4339 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4340 bitmap old_irr, bitmap exit_blocks)
4342 bool any_new_irr = false;
4343 edge e;
4344 edge_iterator ei;
4345 bitmap visited_blocks = BITMAP_ALLOC (NULL);
4349 basic_block bb = pqueue->pop ();
4351 /* Don't re-scan blocks we know already are irrevocable. */
4352 if (old_irr && bitmap_bit_p (old_irr, bb->index))
4353 continue;
4355 if (ipa_tm_scan_irr_block (bb))
4357 bitmap_set_bit (new_irr, bb->index);
4358 any_new_irr = true;
4360 else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4362 FOR_EACH_EDGE (e, ei, bb->succs)
4363 if (!bitmap_bit_p (visited_blocks, e->dest->index))
4365 bitmap_set_bit (visited_blocks, e->dest->index);
4366 pqueue->safe_push (e->dest);
4370 while (!pqueue->is_empty ());
4372 BITMAP_FREE (visited_blocks);
4374 return any_new_irr;
4377 /* Propagate the irrevocable property both up and down the dominator tree.
4378 BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4379 TM regions; OLD_IRR are the results of a previous scan of the dominator
4380 tree which has been fully propagated; NEW_IRR is the set of new blocks
4381 which are gaining the irrevocable property during the current scan. */
4383 static void
4384 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4385 bitmap old_irr, bitmap exit_blocks)
4387 vec<basic_block> bbs;
4388 bitmap all_region_blocks;
4390 /* If this block is in the old set, no need to rescan. */
4391 if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4392 return;
4394 all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4395 bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4396 all_region_blocks, false);
4399 basic_block bb = bbs.pop ();
4400 bool this_irr = bitmap_bit_p (new_irr, bb->index);
4401 bool all_son_irr = false;
4402 edge_iterator ei;
4403 edge e;
4405 /* Propagate up. If my children are, I am too, but we must have
4406 at least one child that is. */
4407 if (!this_irr)
4409 FOR_EACH_EDGE (e, ei, bb->succs)
4411 if (!bitmap_bit_p (new_irr, e->dest->index))
4413 all_son_irr = false;
4414 break;
4416 else
4417 all_son_irr = true;
4419 if (all_son_irr)
4421 /* Add block to new_irr if it hasn't already been processed. */
4422 if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4424 bitmap_set_bit (new_irr, bb->index);
4425 this_irr = true;
4430 /* Propagate down to everyone we immediately dominate. */
4431 if (this_irr)
4433 basic_block son;
4434 for (son = first_dom_son (CDI_DOMINATORS, bb);
4435 son;
4436 son = next_dom_son (CDI_DOMINATORS, son))
4438 /* Make sure block is actually in a TM region, and it
4439 isn't already in old_irr. */
4440 if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4441 && bitmap_bit_p (all_region_blocks, son->index))
4442 bitmap_set_bit (new_irr, son->index);
4446 while (!bbs.is_empty ());
4448 BITMAP_FREE (all_region_blocks);
4449 bbs.release ();
4452 static void
4453 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4455 gimple_stmt_iterator gsi;
4457 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4459 gimple stmt = gsi_stmt (gsi);
4460 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4462 tree fndecl = gimple_call_fndecl (stmt);
4463 if (fndecl)
4465 struct tm_ipa_cg_data *d;
4466 unsigned *pcallers;
4467 struct cgraph_node *tnode;
4469 if (is_tm_ending_fndecl (fndecl))
4470 continue;
4471 if (find_tm_replacement_function (fndecl))
4472 continue;
4474 tnode = cgraph_get_node (fndecl);
4475 d = get_cg_data (&tnode, true);
4477 pcallers = (for_clone ? &d->tm_callers_clone
4478 : &d->tm_callers_normal);
4480 gcc_assert (*pcallers > 0);
4481 *pcallers -= 1;
4487 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4488 as well as other irrevocable actions such as inline assembly. Mark all
4489 such blocks as irrevocable and decrement the number of calls to
4490 transactional clones. Return true if, for the transactional clone, the
4491 entire function is irrevocable. */
4493 static bool
4494 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4496 struct tm_ipa_cg_data *d;
4497 bitmap new_irr, old_irr;
4498 vec<basic_block> queue;
4499 bool ret = false;
4501 /* Builtin operators (operator new, and such). */
4502 if (DECL_STRUCT_FUNCTION (node->decl) == NULL
4503 || DECL_STRUCT_FUNCTION (node->decl)->cfg == NULL)
4504 return false;
4506 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4507 calculate_dominance_info (CDI_DOMINATORS);
4509 d = get_cg_data (&node, true);
4510 queue.create (10);
4511 new_irr = BITMAP_ALLOC (&tm_obstack);
4513 /* Scan each tm region, propagating irrevocable status through the tree. */
4514 if (for_clone)
4516 old_irr = d->irrevocable_blocks_clone;
4517 queue.quick_push (single_succ (ENTRY_BLOCK_PTR));
4518 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4520 ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR), new_irr,
4521 old_irr, NULL);
4522 ret = bitmap_bit_p (new_irr, single_succ (ENTRY_BLOCK_PTR)->index);
4525 else
4527 struct tm_region *region;
4529 old_irr = d->irrevocable_blocks_normal;
4530 for (region = d->all_tm_regions; region; region = region->next)
4532 queue.quick_push (region->entry_block);
4533 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4534 region->exit_blocks))
4535 ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4536 region->exit_blocks);
4540 /* If we found any new irrevocable blocks, reduce the call count for
4541 transactional clones within the irrevocable blocks. Save the new
4542 set of irrevocable blocks for next time. */
4543 if (!bitmap_empty_p (new_irr))
4545 bitmap_iterator bmi;
4546 unsigned i;
4548 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4549 ipa_tm_decrement_clone_counts (BASIC_BLOCK (i), for_clone);
4551 if (old_irr)
4553 bitmap_ior_into (old_irr, new_irr);
4554 BITMAP_FREE (new_irr);
4556 else if (for_clone)
4557 d->irrevocable_blocks_clone = new_irr;
4558 else
4559 d->irrevocable_blocks_normal = new_irr;
4561 if (dump_file && new_irr)
4563 const char *dname;
4564 bitmap_iterator bmi;
4565 unsigned i;
4567 dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4568 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4569 fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4572 else
4573 BITMAP_FREE (new_irr);
4575 queue.release ();
4576 pop_cfun ();
4578 return ret;
4581 /* Return true if, for the transactional clone of NODE, any call
4582 may enter irrevocable mode. */
4584 static bool
4585 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4587 struct tm_ipa_cg_data *d;
4588 tree decl;
4589 unsigned flags;
4591 d = get_cg_data (&node, true);
4592 decl = node->decl;
4593 flags = flags_from_decl_or_type (decl);
4595 /* Handle some TM builtins. Ordinarily these aren't actually generated
4596 at this point, but handling these functions when written in by the
4597 user makes it easier to build unit tests. */
4598 if (flags & ECF_TM_BUILTIN)
4599 return false;
4601 /* Filter out all functions that are marked. */
4602 if (flags & ECF_TM_PURE)
4603 return false;
4604 if (is_tm_safe (decl))
4605 return false;
4606 if (is_tm_irrevocable (decl))
4607 return true;
4608 if (is_tm_callable (decl))
4609 return true;
4610 if (find_tm_replacement_function (decl))
4611 return true;
4613 /* If we aren't seeing the final version of the function we don't
4614 know what it will contain at runtime. */
4615 if (cgraph_function_body_availability (node) < AVAIL_AVAILABLE)
4616 return true;
4618 /* If the function must go irrevocable, then of course true. */
4619 if (d->is_irrevocable)
4620 return true;
4622 /* If there are any blocks marked irrevocable, then the function
4623 as a whole may enter irrevocable. */
4624 if (d->irrevocable_blocks_clone)
4625 return true;
4627 /* We may have previously marked this function as tm_may_enter_irr;
4628 see pass_diagnose_tm_blocks. */
4629 if (node->local.tm_may_enter_irr)
4630 return true;
4632 /* Recurse on the main body for aliases. In general, this will
4633 result in one of the bits above being set so that we will not
4634 have to recurse next time. */
4635 if (node->alias)
4636 return ipa_tm_mayenterirr_function (cgraph_get_node (node->thunk.alias));
4638 /* What remains is unmarked local functions without items that force
4639 the function to go irrevocable. */
4640 return false;
4643 /* Diagnose calls from transaction_safe functions to unmarked
4644 functions that are determined to not be safe. */
4646 static void
4647 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4649 struct cgraph_edge *e;
4651 for (e = node->callees; e ; e = e->next_callee)
4652 if (!is_tm_callable (e->callee->decl)
4653 && e->callee->local.tm_may_enter_irr)
4654 error_at (gimple_location (e->call_stmt),
4655 "unsafe function call %qD within "
4656 "%<transaction_safe%> function", e->callee->decl);
4659 /* Diagnose call from atomic transactions to unmarked functions
4660 that are determined to not be safe. */
4662 static void
4663 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4664 struct tm_region *all_tm_regions)
4666 struct tm_region *r;
4668 for (r = all_tm_regions; r ; r = r->next)
4669 if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4671 /* Atomic transactions can be nested inside relaxed. */
4672 if (r->inner)
4673 ipa_tm_diagnose_transaction (node, r->inner);
4675 else
4677 vec<basic_block> bbs;
4678 gimple_stmt_iterator gsi;
4679 basic_block bb;
4680 size_t i;
4682 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4683 r->irr_blocks, NULL, false);
4685 for (i = 0; bbs.iterate (i, &bb); ++i)
4686 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4688 gimple stmt = gsi_stmt (gsi);
4689 tree fndecl;
4691 if (gimple_code (stmt) == GIMPLE_ASM)
4693 error_at (gimple_location (stmt),
4694 "asm not allowed in atomic transaction");
4695 continue;
4698 if (!is_gimple_call (stmt))
4699 continue;
4700 fndecl = gimple_call_fndecl (stmt);
4702 /* Indirect function calls have been diagnosed already. */
4703 if (!fndecl)
4704 continue;
4706 /* Stop at the end of the transaction. */
4707 if (is_tm_ending_fndecl (fndecl))
4709 if (bitmap_bit_p (r->exit_blocks, bb->index))
4710 break;
4711 continue;
4714 /* Marked functions have been diagnosed already. */
4715 if (is_tm_pure_call (stmt))
4716 continue;
4717 if (is_tm_callable (fndecl))
4718 continue;
4720 if (cgraph_local_info (fndecl)->tm_may_enter_irr)
4721 error_at (gimple_location (stmt),
4722 "unsafe function call %qD within "
4723 "atomic transaction", fndecl);
4726 bbs.release ();
4730 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4731 OLD_DECL. The returned value is a freshly malloced pointer that
4732 should be freed by the caller. */
4734 static tree
4735 tm_mangle (tree old_asm_id)
4737 const char *old_asm_name;
4738 char *tm_name;
4739 void *alloc = NULL;
4740 struct demangle_component *dc;
4741 tree new_asm_id;
4743 /* Determine if the symbol is already a valid C++ mangled name. Do this
4744 even for C, which might be interfacing with C++ code via appropriately
4745 ugly identifiers. */
4746 /* ??? We could probably do just as well checking for "_Z" and be done. */
4747 old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4748 dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4750 if (dc == NULL)
4752 char length[8];
4754 do_unencoded:
4755 sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4756 tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4758 else
4760 old_asm_name += 2; /* Skip _Z */
4762 switch (dc->type)
4764 case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4765 case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4766 /* Don't play silly games, you! */
4767 goto do_unencoded;
4769 case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4770 /* I'd really like to know if we can ever be passed one of
4771 these from the C++ front end. The Logical Thing would
4772 seem that hidden-alias should be outer-most, so that we
4773 get hidden-alias of a transaction-clone and not vice-versa. */
4774 old_asm_name += 2;
4775 break;
4777 default:
4778 break;
4781 tm_name = concat ("_ZGTt", old_asm_name, NULL);
4783 free (alloc);
4785 new_asm_id = get_identifier (tm_name);
4786 free (tm_name);
4788 return new_asm_id;
4791 static inline void
4792 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4794 cgraph_mark_force_output_node (node);
4795 node->analyzed = true;
4798 static inline void
4799 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4801 node->forced_by_abi = true;
4802 node->analyzed = true;
4805 /* Callback data for ipa_tm_create_version_alias. */
4806 struct create_version_alias_info
4808 struct cgraph_node *old_node;
4809 tree new_decl;
4812 /* A subroutine of ipa_tm_create_version, called via
4813 cgraph_for_node_and_aliases. Create new tm clones for each of
4814 the existing aliases. */
4815 static bool
4816 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4818 struct create_version_alias_info *info
4819 = (struct create_version_alias_info *)data;
4820 tree old_decl, new_decl, tm_name;
4821 struct cgraph_node *new_node;
4823 if (!node->cpp_implicit_alias)
4824 return false;
4826 old_decl = node->decl;
4827 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4828 new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4829 TREE_CODE (old_decl), tm_name,
4830 TREE_TYPE (old_decl));
4832 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4833 SET_DECL_RTL (new_decl, NULL);
4835 /* Based loosely on C++'s make_alias_for(). */
4836 TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4837 DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4838 DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4839 TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4840 DECL_EXTERNAL (new_decl) = 0;
4841 DECL_ARTIFICIAL (new_decl) = 1;
4842 TREE_ADDRESSABLE (new_decl) = 1;
4843 TREE_USED (new_decl) = 1;
4844 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4846 /* Perform the same remapping to the comdat group. */
4847 if (DECL_ONE_ONLY (new_decl))
4848 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4850 new_node = cgraph_same_body_alias (NULL, new_decl, info->new_decl);
4851 new_node->tm_clone = true;
4852 new_node->externally_visible = info->old_node->externally_visible;
4853 /* ?? Do not traverse aliases here. */
4854 get_cg_data (&node, false)->clone = new_node;
4856 record_tm_clone_pair (old_decl, new_decl);
4858 if (info->old_node->force_output
4859 || ipa_ref_list_first_referring (&info->old_node->ref_list))
4860 ipa_tm_mark_force_output_node (new_node);
4861 if (info->old_node->forced_by_abi)
4862 ipa_tm_mark_forced_by_abi_node (new_node);
4863 return false;
4866 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4867 appropriate for the transactional clone. */
4869 static void
4870 ipa_tm_create_version (struct cgraph_node *old_node)
4872 tree new_decl, old_decl, tm_name;
4873 struct cgraph_node *new_node;
4875 old_decl = old_node->decl;
4876 new_decl = copy_node (old_decl);
4878 /* DECL_ASSEMBLER_NAME needs to be set before we call
4879 cgraph_copy_node_for_versioning below, because cgraph_node will
4880 fill the assembler_name_hash. */
4881 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4882 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4883 SET_DECL_RTL (new_decl, NULL);
4884 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4886 /* Perform the same remapping to the comdat group. */
4887 if (DECL_ONE_ONLY (new_decl))
4888 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4890 new_node = cgraph_copy_node_for_versioning (old_node, new_decl, vNULL, NULL);
4891 new_node->local.local = false;
4892 new_node->externally_visible = old_node->externally_visible;
4893 new_node->lowered = true;
4894 new_node->tm_clone = 1;
4895 get_cg_data (&old_node, true)->clone = new_node;
4897 if (cgraph_function_body_availability (old_node) >= AVAIL_OVERWRITABLE)
4899 /* Remap extern inline to static inline. */
4900 /* ??? Is it worth trying to use make_decl_one_only? */
4901 if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4903 DECL_EXTERNAL (new_decl) = 0;
4904 TREE_PUBLIC (new_decl) = 0;
4905 DECL_WEAK (new_decl) = 0;
4908 tree_function_versioning (old_decl, new_decl,
4909 NULL, false, NULL,
4910 false, NULL, NULL);
4913 record_tm_clone_pair (old_decl, new_decl);
4915 cgraph_call_function_insertion_hooks (new_node);
4916 if (old_node->force_output
4917 || ipa_ref_list_first_referring (&old_node->ref_list))
4918 ipa_tm_mark_force_output_node (new_node);
4919 if (old_node->forced_by_abi)
4920 ipa_tm_mark_forced_by_abi_node (new_node);
4922 /* Do the same thing, but for any aliases of the original node. */
4924 struct create_version_alias_info data;
4925 data.old_node = old_node;
4926 data.new_decl = new_decl;
4927 cgraph_for_node_and_aliases (old_node, ipa_tm_create_version_alias,
4928 &data, true);
4932 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB. */
4934 static void
4935 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4936 basic_block bb)
4938 gimple_stmt_iterator gsi;
4939 gimple g;
4941 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4943 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4944 1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4946 split_block_after_labels (bb);
4947 gsi = gsi_after_labels (bb);
4948 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4950 cgraph_create_edge (node,
4951 cgraph_get_create_node
4952 (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4953 g, 0,
4954 compute_call_stmt_bb_frequency (node->decl,
4955 gimple_bb (g)));
4958 /* Construct a call to TM_GETTMCLONE and insert it before GSI. */
4960 static bool
4961 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4962 struct tm_region *region,
4963 gimple_stmt_iterator *gsi, gimple stmt)
4965 tree gettm_fn, ret, old_fn, callfn;
4966 gimple g, g2;
4967 bool safe;
4969 old_fn = gimple_call_fn (stmt);
4971 if (TREE_CODE (old_fn) == ADDR_EXPR)
4973 tree fndecl = TREE_OPERAND (old_fn, 0);
4974 tree clone = get_tm_clone_pair (fndecl);
4976 /* By transforming the call into a TM_GETTMCLONE, we are
4977 technically taking the address of the original function and
4978 its clone. Explain this so inlining will know this function
4979 is needed. */
4980 cgraph_mark_address_taken_node (cgraph_get_node (fndecl));
4981 if (clone)
4982 cgraph_mark_address_taken_node (cgraph_get_node (clone));
4985 safe = is_tm_safe (TREE_TYPE (old_fn));
4986 gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
4987 : BUILT_IN_TM_GETTMCLONE_IRR);
4988 ret = create_tmp_var (ptr_type_node, NULL);
4990 if (!safe)
4991 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4993 /* Discard OBJ_TYPE_REF, since we weren't able to fold it. */
4994 if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
4995 old_fn = OBJ_TYPE_REF_EXPR (old_fn);
4997 g = gimple_build_call (gettm_fn, 1, old_fn);
4998 ret = make_ssa_name (ret, g);
4999 gimple_call_set_lhs (g, ret);
5001 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5003 cgraph_create_edge (node, cgraph_get_create_node (gettm_fn), g, 0,
5004 compute_call_stmt_bb_frequency (node->decl,
5005 gimple_bb (g)));
5007 /* Cast return value from tm_gettmclone* into appropriate function
5008 pointer. */
5009 callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
5010 g2 = gimple_build_assign (callfn,
5011 fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5012 callfn = make_ssa_name (callfn, g2);
5013 gimple_assign_set_lhs (g2, callfn);
5014 gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5016 /* ??? This is a hack to preserve the NOTHROW bit on the call,
5017 which we would have derived from the decl. Failure to save
5018 this bit means we might have to split the basic block. */
5019 if (gimple_call_nothrow_p (stmt))
5020 gimple_call_set_nothrow (stmt, true);
5022 gimple_call_set_fn (stmt, callfn);
5024 /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5025 for a call statement. Fix it. */
5027 tree lhs = gimple_call_lhs (stmt);
5028 tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5029 if (lhs
5030 && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5032 tree temp;
5034 temp = create_tmp_reg (rettype, 0);
5035 gimple_call_set_lhs (stmt, temp);
5037 g2 = gimple_build_assign (lhs,
5038 fold_build1 (VIEW_CONVERT_EXPR,
5039 TREE_TYPE (lhs), temp));
5040 gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5044 update_stmt (stmt);
5046 return true;
5049 /* Helper function for ipa_tm_transform_calls*. Given a call
5050 statement in GSI which resides inside transaction REGION, redirect
5051 the call to either its wrapper function, or its clone. */
5053 static void
5054 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5055 struct tm_region *region,
5056 gimple_stmt_iterator *gsi,
5057 bool *need_ssa_rename_p)
5059 gimple stmt = gsi_stmt (*gsi);
5060 struct cgraph_node *new_node;
5061 struct cgraph_edge *e = cgraph_edge (node, stmt);
5062 tree fndecl = gimple_call_fndecl (stmt);
5064 /* For indirect calls, pass the address through the runtime. */
5065 if (fndecl == NULL)
5067 *need_ssa_rename_p |=
5068 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5069 return;
5072 /* Handle some TM builtins. Ordinarily these aren't actually generated
5073 at this point, but handling these functions when written in by the
5074 user makes it easier to build unit tests. */
5075 if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5076 return;
5078 /* Fixup recursive calls inside clones. */
5079 /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5080 for recursion but not update the call statements themselves? */
5081 if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5083 gimple_call_set_fndecl (stmt, current_function_decl);
5084 return;
5087 /* If there is a replacement, use it. */
5088 fndecl = find_tm_replacement_function (fndecl);
5089 if (fndecl)
5091 new_node = cgraph_get_create_node (fndecl);
5093 /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5095 We can't do this earlier in record_tm_replacement because
5096 cgraph_remove_unreachable_nodes is called before we inject
5097 references to the node. Further, we can't do this in some
5098 nice central place in ipa_tm_execute because we don't have
5099 the exact list of wrapper functions that would be used.
5100 Marking more wrappers than necessary results in the creation
5101 of unnecessary cgraph_nodes, which can cause some of the
5102 other IPA passes to crash.
5104 We do need to mark these nodes so that we get the proper
5105 result in expand_call_tm. */
5106 /* ??? This seems broken. How is it that we're marking the
5107 CALLEE as may_enter_irr? Surely we should be marking the
5108 CALLER. Also note that find_tm_replacement_function also
5109 contains mappings into the TM runtime, e.g. memcpy. These
5110 we know won't go irrevocable. */
5111 new_node->local.tm_may_enter_irr = 1;
5113 else
5115 struct tm_ipa_cg_data *d;
5116 struct cgraph_node *tnode = e->callee;
5118 d = get_cg_data (&tnode, true);
5119 new_node = d->clone;
5121 /* As we've already skipped pure calls and appropriate builtins,
5122 and we've already marked irrevocable blocks, if we can't come
5123 up with a static replacement, then ask the runtime. */
5124 if (new_node == NULL)
5126 *need_ssa_rename_p |=
5127 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5128 return;
5131 fndecl = new_node->decl;
5134 cgraph_redirect_edge_callee (e, new_node);
5135 gimple_call_set_fndecl (stmt, fndecl);
5138 /* Helper function for ipa_tm_transform_calls. For a given BB,
5139 install calls to tm_irrevocable when IRR_BLOCKS are reached,
5140 redirect other calls to the generated transactional clone. */
5142 static bool
5143 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5144 basic_block bb, bitmap irr_blocks)
5146 gimple_stmt_iterator gsi;
5147 bool need_ssa_rename = false;
5149 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5151 ipa_tm_insert_irr_call (node, region, bb);
5152 return true;
5155 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5157 gimple stmt = gsi_stmt (gsi);
5159 if (!is_gimple_call (stmt))
5160 continue;
5161 if (is_tm_pure_call (stmt))
5162 continue;
5164 /* Redirect edges to the appropriate replacement or clone. */
5165 ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5168 return need_ssa_rename;
5171 /* Walk the CFG for REGION, beginning at BB. Install calls to
5172 tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5173 the generated transactional clone. */
5175 static bool
5176 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5177 basic_block bb, bitmap irr_blocks)
5179 bool need_ssa_rename = false;
5180 edge e;
5181 edge_iterator ei;
5182 vec<basic_block> queue = vNULL;
5183 bitmap visited_blocks = BITMAP_ALLOC (NULL);
5185 queue.safe_push (bb);
5188 bb = queue.pop ();
5190 need_ssa_rename |=
5191 ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5193 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5194 continue;
5196 if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5197 continue;
5199 FOR_EACH_EDGE (e, ei, bb->succs)
5200 if (!bitmap_bit_p (visited_blocks, e->dest->index))
5202 bitmap_set_bit (visited_blocks, e->dest->index);
5203 queue.safe_push (e->dest);
5206 while (!queue.is_empty ());
5208 queue.release ();
5209 BITMAP_FREE (visited_blocks);
5211 return need_ssa_rename;
5214 /* Transform the calls within the TM regions within NODE. */
5216 static void
5217 ipa_tm_transform_transaction (struct cgraph_node *node)
5219 struct tm_ipa_cg_data *d;
5220 struct tm_region *region;
5221 bool need_ssa_rename = false;
5223 d = get_cg_data (&node, true);
5225 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5226 calculate_dominance_info (CDI_DOMINATORS);
5228 for (region = d->all_tm_regions; region; region = region->next)
5230 /* If we're sure to go irrevocable, don't transform anything. */
5231 if (d->irrevocable_blocks_normal
5232 && bitmap_bit_p (d->irrevocable_blocks_normal,
5233 region->entry_block->index))
5235 transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5236 | GTMA_MAY_ENTER_IRREVOCABLE
5237 | GTMA_HAS_NO_INSTRUMENTATION);
5238 continue;
5241 need_ssa_rename |=
5242 ipa_tm_transform_calls (node, region, region->entry_block,
5243 d->irrevocable_blocks_normal);
5246 if (need_ssa_rename)
5247 update_ssa (TODO_update_ssa_only_virtuals);
5249 pop_cfun ();
5252 /* Transform the calls within the transactional clone of NODE. */
5254 static void
5255 ipa_tm_transform_clone (struct cgraph_node *node)
5257 struct tm_ipa_cg_data *d;
5258 bool need_ssa_rename;
5260 d = get_cg_data (&node, true);
5262 /* If this function makes no calls and has no irrevocable blocks,
5263 then there's nothing to do. */
5264 /* ??? Remove non-aborting top-level transactions. */
5265 if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5266 return;
5268 push_cfun (DECL_STRUCT_FUNCTION (d->clone->decl));
5269 calculate_dominance_info (CDI_DOMINATORS);
5271 need_ssa_rename =
5272 ipa_tm_transform_calls (d->clone, NULL, single_succ (ENTRY_BLOCK_PTR),
5273 d->irrevocable_blocks_clone);
5275 if (need_ssa_rename)
5276 update_ssa (TODO_update_ssa_only_virtuals);
5278 pop_cfun ();
5281 /* Main entry point for the transactional memory IPA pass. */
5283 static unsigned int
5284 ipa_tm_execute (void)
5286 cgraph_node_queue tm_callees = cgraph_node_queue ();
5287 /* List of functions that will go irrevocable. */
5288 cgraph_node_queue irr_worklist = cgraph_node_queue ();
5290 struct cgraph_node *node;
5291 struct tm_ipa_cg_data *d;
5292 enum availability a;
5293 unsigned int i;
5295 #ifdef ENABLE_CHECKING
5296 verify_cgraph ();
5297 #endif
5299 bitmap_obstack_initialize (&tm_obstack);
5300 initialize_original_copy_tables ();
5302 /* For all local functions marked tm_callable, queue them. */
5303 FOR_EACH_DEFINED_FUNCTION (node)
5304 if (is_tm_callable (node->decl)
5305 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5307 d = get_cg_data (&node, true);
5308 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5311 /* For all local reachable functions... */
5312 FOR_EACH_DEFINED_FUNCTION (node)
5313 if (node->lowered
5314 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5316 /* ... marked tm_pure, record that fact for the runtime by
5317 indicating that the pure function is its own tm_callable.
5318 No need to do this if the function's address can't be taken. */
5319 if (is_tm_pure (node->decl))
5321 if (!node->local.local)
5322 record_tm_clone_pair (node->decl, node->decl);
5323 continue;
5326 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5327 calculate_dominance_info (CDI_DOMINATORS);
5329 tm_region_init (NULL);
5330 if (all_tm_regions)
5332 d = get_cg_data (&node, true);
5334 /* Scan for calls that are in each transaction, and
5335 generate the uninstrumented code path. */
5336 ipa_tm_scan_calls_transaction (d, &tm_callees);
5338 /* Put it in the worklist so we can scan the function
5339 later (ipa_tm_scan_irr_function) and mark the
5340 irrevocable blocks. */
5341 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5342 d->want_irr_scan_normal = true;
5345 pop_cfun ();
5348 /* For every local function on the callee list, scan as if we will be
5349 creating a transactional clone, queueing all new functions we find
5350 along the way. */
5351 for (i = 0; i < tm_callees.length (); ++i)
5353 node = tm_callees[i];
5354 a = cgraph_function_body_availability (node);
5355 d = get_cg_data (&node, true);
5357 /* Put it in the worklist so we can scan the function later
5358 (ipa_tm_scan_irr_function) and mark the irrevocable
5359 blocks. */
5360 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5362 /* Some callees cannot be arbitrarily cloned. These will always be
5363 irrevocable. Mark these now, so that we need not scan them. */
5364 if (is_tm_irrevocable (node->decl))
5365 ipa_tm_note_irrevocable (node, &irr_worklist);
5366 else if (a <= AVAIL_NOT_AVAILABLE
5367 && !is_tm_safe_or_pure (node->decl))
5368 ipa_tm_note_irrevocable (node, &irr_worklist);
5369 else if (a >= AVAIL_OVERWRITABLE)
5371 if (!tree_versionable_function_p (node->decl))
5372 ipa_tm_note_irrevocable (node, &irr_worklist);
5373 else if (!d->is_irrevocable)
5375 /* If this is an alias, make sure its base is queued as well.
5376 we need not scan the callees now, as the base will do. */
5377 if (node->alias)
5379 node = cgraph_get_node (node->thunk.alias);
5380 d = get_cg_data (&node, true);
5381 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5382 continue;
5385 /* Add all nodes called by this function into
5386 tm_callees as well. */
5387 ipa_tm_scan_calls_clone (node, &tm_callees);
5392 /* Iterate scans until no more work to be done. Prefer not to use
5393 vec::pop because the worklist tends to follow a breadth-first
5394 search of the callgraph, which should allow convergance with a
5395 minimum number of scans. But we also don't want the worklist
5396 array to grow without bound, so we shift the array up periodically. */
5397 for (i = 0; i < irr_worklist.length (); ++i)
5399 if (i > 256 && i == irr_worklist.length () / 8)
5401 irr_worklist.block_remove (0, i);
5402 i = 0;
5405 node = irr_worklist[i];
5406 d = get_cg_data (&node, true);
5407 d->in_worklist = false;
5409 if (d->want_irr_scan_normal)
5411 d->want_irr_scan_normal = false;
5412 ipa_tm_scan_irr_function (node, false);
5414 if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5415 ipa_tm_note_irrevocable (node, &irr_worklist);
5418 /* For every function on the callee list, collect the tm_may_enter_irr
5419 bit on the node. */
5420 irr_worklist.truncate (0);
5421 for (i = 0; i < tm_callees.length (); ++i)
5423 node = tm_callees[i];
5424 if (ipa_tm_mayenterirr_function (node))
5426 d = get_cg_data (&node, true);
5427 gcc_assert (d->in_worklist == false);
5428 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5432 /* Propagate the tm_may_enter_irr bit to callers until stable. */
5433 for (i = 0; i < irr_worklist.length (); ++i)
5435 struct cgraph_node *caller;
5436 struct cgraph_edge *e;
5437 struct ipa_ref *ref;
5438 unsigned j;
5440 if (i > 256 && i == irr_worklist.length () / 8)
5442 irr_worklist.block_remove (0, i);
5443 i = 0;
5446 node = irr_worklist[i];
5447 d = get_cg_data (&node, true);
5448 d->in_worklist = false;
5449 node->local.tm_may_enter_irr = true;
5451 /* Propagate back to normal callers. */
5452 for (e = node->callers; e ; e = e->next_caller)
5454 caller = e->caller;
5455 if (!is_tm_safe_or_pure (caller->decl)
5456 && !caller->local.tm_may_enter_irr)
5458 d = get_cg_data (&caller, true);
5459 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5463 /* Propagate back to referring aliases as well. */
5464 for (j = 0; ipa_ref_list_referring_iterate (&node->ref_list, j, ref); j++)
5466 caller = cgraph (ref->referring);
5467 if (ref->use == IPA_REF_ALIAS
5468 && !caller->local.tm_may_enter_irr)
5470 /* ?? Do not traverse aliases here. */
5471 d = get_cg_data (&caller, false);
5472 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5477 /* Now validate all tm_safe functions, and all atomic regions in
5478 other functions. */
5479 FOR_EACH_DEFINED_FUNCTION (node)
5480 if (node->lowered
5481 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5483 d = get_cg_data (&node, true);
5484 if (is_tm_safe (node->decl))
5485 ipa_tm_diagnose_tm_safe (node);
5486 else if (d->all_tm_regions)
5487 ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5490 /* Create clones. Do those that are not irrevocable and have a
5491 positive call count. Do those publicly visible functions that
5492 the user directed us to clone. */
5493 for (i = 0; i < tm_callees.length (); ++i)
5495 bool doit = false;
5497 node = tm_callees[i];
5498 if (node->cpp_implicit_alias)
5499 continue;
5501 a = cgraph_function_body_availability (node);
5502 d = get_cg_data (&node, true);
5504 if (a <= AVAIL_NOT_AVAILABLE)
5505 doit = is_tm_callable (node->decl);
5506 else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
5507 doit = true;
5508 else if (!d->is_irrevocable
5509 && d->tm_callers_normal + d->tm_callers_clone > 0)
5510 doit = true;
5512 if (doit)
5513 ipa_tm_create_version (node);
5516 /* Redirect calls to the new clones, and insert irrevocable marks. */
5517 for (i = 0; i < tm_callees.length (); ++i)
5519 node = tm_callees[i];
5520 if (node->analyzed)
5522 d = get_cg_data (&node, true);
5523 if (d->clone)
5524 ipa_tm_transform_clone (node);
5527 FOR_EACH_DEFINED_FUNCTION (node)
5528 if (node->lowered
5529 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5531 d = get_cg_data (&node, true);
5532 if (d->all_tm_regions)
5533 ipa_tm_transform_transaction (node);
5536 /* Free and clear all data structures. */
5537 tm_callees.release ();
5538 irr_worklist.release ();
5539 bitmap_obstack_release (&tm_obstack);
5540 free_original_copy_tables ();
5542 FOR_EACH_FUNCTION (node)
5543 node->aux = NULL;
5545 #ifdef ENABLE_CHECKING
5546 verify_cgraph ();
5547 #endif
5549 return 0;
5552 namespace {
5554 const pass_data pass_data_ipa_tm =
5556 SIMPLE_IPA_PASS, /* type */
5557 "tmipa", /* name */
5558 OPTGROUP_NONE, /* optinfo_flags */
5559 true, /* has_gate */
5560 true, /* has_execute */
5561 TV_TRANS_MEM, /* tv_id */
5562 ( PROP_ssa | PROP_cfg ), /* properties_required */
5563 0, /* properties_provided */
5564 0, /* properties_destroyed */
5565 0, /* todo_flags_start */
5566 0, /* todo_flags_finish */
5569 class pass_ipa_tm : public simple_ipa_opt_pass
5571 public:
5572 pass_ipa_tm (gcc::context *ctxt)
5573 : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5576 /* opt_pass methods: */
5577 bool gate () { return gate_tm (); }
5578 unsigned int execute () { return ipa_tm_execute (); }
5580 }; // class pass_ipa_tm
5582 } // anon namespace
5584 simple_ipa_opt_pass *
5585 make_pass_ipa_tm (gcc::context *ctxt)
5587 return new pass_ipa_tm (ctxt);
5590 #include "gt-trans-mem.h"