Merge from trunk: 215733-215743
[official-gcc.git] / gcc-4_9 / gcc / trans-mem.c
blob73afb2384ea4c3273c4e11bf90088678303ad4b4
1 /* Passes for transactional memory support.
2 Copyright (C) 2008-2014 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 "basic-block.h"
26 #include "tree-ssa-alias.h"
27 #include "internal-fn.h"
28 #include "tree-eh.h"
29 #include "gimple-expr.h"
30 #include "is-a.h"
31 #include "gimple.h"
32 #include "calls.h"
33 #include "function.h"
34 #include "rtl.h"
35 #include "emit-rtl.h"
36 #include "gimplify.h"
37 #include "gimple-iterator.h"
38 #include "gimplify-me.h"
39 #include "gimple-walk.h"
40 #include "gimple-ssa.h"
41 #include "cgraph.h"
42 #include "tree-cfg.h"
43 #include "stringpool.h"
44 #include "tree-ssanames.h"
45 #include "tree-into-ssa.h"
46 #include "tree-pass.h"
47 #include "tree-inline.h"
48 #include "diagnostic-core.h"
49 #include "demangle.h"
50 #include "output.h"
51 #include "trans-mem.h"
52 #include "params.h"
53 #include "target.h"
54 #include "langhooks.h"
55 #include "gimple-pretty-print.h"
56 #include "cfgloop.h"
57 #include "tree-ssa-address.h"
58 #include "predict.h"
61 #define A_RUNINSTRUMENTEDCODE 0x0001
62 #define A_RUNUNINSTRUMENTEDCODE 0x0002
63 #define A_SAVELIVEVARIABLES 0x0004
64 #define A_RESTORELIVEVARIABLES 0x0008
65 #define A_ABORTTRANSACTION 0x0010
67 #define AR_USERABORT 0x0001
68 #define AR_USERRETRY 0x0002
69 #define AR_TMCONFLICT 0x0004
70 #define AR_EXCEPTIONBLOCKABORT 0x0008
71 #define AR_OUTERABORT 0x0010
73 #define MODE_SERIALIRREVOCABLE 0x0000
76 /* The representation of a transaction changes several times during the
77 lowering process. In the beginning, in the front-end we have the
78 GENERIC tree TRANSACTION_EXPR. For example,
80 __transaction {
81 local++;
82 if (++global == 10)
83 __tm_abort;
86 During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
87 trivially replaced with a GIMPLE_TRANSACTION node.
89 During pass_lower_tm, we examine the body of transactions looking
90 for aborts. Transactions that do not contain an abort may be
91 merged into an outer transaction. We also add a TRY-FINALLY node
92 to arrange for the transaction to be committed on any exit.
94 [??? Think about how this arrangement affects throw-with-commit
95 and throw-with-abort operations. In this case we want the TRY to
96 handle gotos, but not to catch any exceptions because the transaction
97 will already be closed.]
99 GIMPLE_TRANSACTION [label=NULL] {
100 try {
101 local = local + 1;
102 t0 = global;
103 t1 = t0 + 1;
104 global = t1;
105 if (t1 == 10)
106 __builtin___tm_abort ();
107 } finally {
108 __builtin___tm_commit ();
112 During pass_lower_eh, we create EH regions for the transactions,
113 intermixed with the regular EH stuff. This gives us a nice persistent
114 mapping (all the way through rtl) from transactional memory operation
115 back to the transaction, which allows us to get the abnormal edges
116 correct to model transaction aborts and restarts:
118 GIMPLE_TRANSACTION [label=over]
119 local = local + 1;
120 t0 = global;
121 t1 = t0 + 1;
122 global = t1;
123 if (t1 == 10)
124 __builtin___tm_abort ();
125 __builtin___tm_commit ();
126 over:
128 This is the end of all_lowering_passes, and so is what is present
129 during the IPA passes, and through all of the optimization passes.
131 During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
132 functions and mark functions for cloning.
134 At the end of gimple optimization, before exiting SSA form,
135 pass_tm_edges replaces statements that perform transactional
136 memory operations with the appropriate TM builtins, and swap
137 out function calls with their transactional clones. At this
138 point we introduce the abnormal transaction restart edges and
139 complete lowering of the GIMPLE_TRANSACTION node.
141 x = __builtin___tm_start (MAY_ABORT);
142 eh_label:
143 if (x & abort_transaction)
144 goto over;
145 local = local + 1;
146 t0 = __builtin___tm_load (global);
147 t1 = t0 + 1;
148 __builtin___tm_store (&global, t1);
149 if (t1 == 10)
150 __builtin___tm_abort ();
151 __builtin___tm_commit ();
152 over:
155 static void *expand_regions (struct tm_region *,
156 void *(*callback)(struct tm_region *, void *),
157 void *, bool);
160 /* Return the attributes we want to examine for X, or NULL if it's not
161 something we examine. We look at function types, but allow pointers
162 to function types and function decls and peek through. */
164 static tree
165 get_attrs_for (const_tree x)
167 if (x == NULL_TREE)
168 return NULL_TREE;
170 switch (TREE_CODE (x))
172 case FUNCTION_DECL:
173 return TYPE_ATTRIBUTES (TREE_TYPE (x));
174 break;
176 default:
177 if (TYPE_P (x))
178 return NULL_TREE;
179 x = TREE_TYPE (x);
180 if (TREE_CODE (x) != POINTER_TYPE)
181 return NULL_TREE;
182 /* FALLTHRU */
184 case POINTER_TYPE:
185 x = TREE_TYPE (x);
186 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
187 return NULL_TREE;
188 /* FALLTHRU */
190 case FUNCTION_TYPE:
191 case METHOD_TYPE:
192 return TYPE_ATTRIBUTES (x);
196 /* Return true if X has been marked TM_PURE. */
198 bool
199 is_tm_pure (const_tree x)
201 unsigned flags;
203 switch (TREE_CODE (x))
205 case FUNCTION_DECL:
206 case FUNCTION_TYPE:
207 case METHOD_TYPE:
208 break;
210 default:
211 if (TYPE_P (x))
212 return false;
213 x = TREE_TYPE (x);
214 if (TREE_CODE (x) != POINTER_TYPE)
215 return false;
216 /* FALLTHRU */
218 case POINTER_TYPE:
219 x = TREE_TYPE (x);
220 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
221 return false;
222 break;
225 flags = flags_from_decl_or_type (x);
226 return (flags & ECF_TM_PURE) != 0;
229 /* Return true if X has been marked TM_IRREVOCABLE. */
231 static bool
232 is_tm_irrevocable (tree x)
234 tree attrs = get_attrs_for (x);
236 if (attrs && lookup_attribute ("transaction_unsafe", attrs))
237 return true;
239 /* A call to the irrevocable builtin is by definition,
240 irrevocable. */
241 if (TREE_CODE (x) == ADDR_EXPR)
242 x = TREE_OPERAND (x, 0);
243 if (TREE_CODE (x) == FUNCTION_DECL
244 && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
245 && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
246 return true;
248 return false;
251 /* Return true if X has been marked TM_SAFE. */
253 bool
254 is_tm_safe (const_tree x)
256 if (flag_tm)
258 tree attrs = get_attrs_for (x);
259 if (attrs)
261 if (lookup_attribute ("transaction_safe", attrs))
262 return true;
263 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
264 return true;
267 return false;
270 /* Return true if CALL is const, or tm_pure. */
272 static bool
273 is_tm_pure_call (gimple call)
275 tree fn = gimple_call_fn (call);
277 if (TREE_CODE (fn) == ADDR_EXPR)
279 fn = TREE_OPERAND (fn, 0);
280 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
282 else
283 fn = TREE_TYPE (fn);
285 return is_tm_pure (fn);
288 /* Return true if X has been marked TM_CALLABLE. */
290 static bool
291 is_tm_callable (tree x)
293 tree attrs = get_attrs_for (x);
294 if (attrs)
296 if (lookup_attribute ("transaction_callable", attrs))
297 return true;
298 if (lookup_attribute ("transaction_safe", attrs))
299 return true;
300 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
301 return true;
303 return false;
306 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER. */
308 bool
309 is_tm_may_cancel_outer (tree x)
311 tree attrs = get_attrs_for (x);
312 if (attrs)
313 return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
314 return false;
317 /* Return true for built in functions that "end" a transaction. */
319 bool
320 is_tm_ending_fndecl (tree fndecl)
322 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
323 switch (DECL_FUNCTION_CODE (fndecl))
325 case BUILT_IN_TM_COMMIT:
326 case BUILT_IN_TM_COMMIT_EH:
327 case BUILT_IN_TM_ABORT:
328 case BUILT_IN_TM_IRREVOCABLE:
329 return true;
330 default:
331 break;
334 return false;
337 /* Return true if STMT is a built in function call that "ends" a
338 transaction. */
340 bool
341 is_tm_ending (gimple stmt)
343 tree fndecl;
345 if (gimple_code (stmt) != GIMPLE_CALL)
346 return false;
348 fndecl = gimple_call_fndecl (stmt);
349 return (fndecl != NULL_TREE
350 && is_tm_ending_fndecl (fndecl));
353 /* Return true if STMT is a TM load. */
355 static bool
356 is_tm_load (gimple stmt)
358 tree fndecl;
360 if (gimple_code (stmt) != GIMPLE_CALL)
361 return false;
363 fndecl = gimple_call_fndecl (stmt);
364 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
365 && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
368 /* Same as above, but for simple TM loads, that is, not the
369 after-write, after-read, etc optimized variants. */
371 static bool
372 is_tm_simple_load (gimple stmt)
374 tree fndecl;
376 if (gimple_code (stmt) != GIMPLE_CALL)
377 return false;
379 fndecl = gimple_call_fndecl (stmt);
380 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
382 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
383 return (fcode == BUILT_IN_TM_LOAD_1
384 || fcode == BUILT_IN_TM_LOAD_2
385 || fcode == BUILT_IN_TM_LOAD_4
386 || fcode == BUILT_IN_TM_LOAD_8
387 || fcode == BUILT_IN_TM_LOAD_FLOAT
388 || fcode == BUILT_IN_TM_LOAD_DOUBLE
389 || fcode == BUILT_IN_TM_LOAD_LDOUBLE
390 || fcode == BUILT_IN_TM_LOAD_M64
391 || fcode == BUILT_IN_TM_LOAD_M128
392 || fcode == BUILT_IN_TM_LOAD_M256);
394 return false;
397 /* Return true if STMT is a TM store. */
399 static bool
400 is_tm_store (gimple stmt)
402 tree fndecl;
404 if (gimple_code (stmt) != GIMPLE_CALL)
405 return false;
407 fndecl = gimple_call_fndecl (stmt);
408 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
409 && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
412 /* Same as above, but for simple TM stores, that is, not the
413 after-write, after-read, etc optimized variants. */
415 static bool
416 is_tm_simple_store (gimple stmt)
418 tree fndecl;
420 if (gimple_code (stmt) != GIMPLE_CALL)
421 return false;
423 fndecl = gimple_call_fndecl (stmt);
424 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
426 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
427 return (fcode == BUILT_IN_TM_STORE_1
428 || fcode == BUILT_IN_TM_STORE_2
429 || fcode == BUILT_IN_TM_STORE_4
430 || fcode == BUILT_IN_TM_STORE_8
431 || fcode == BUILT_IN_TM_STORE_FLOAT
432 || fcode == BUILT_IN_TM_STORE_DOUBLE
433 || fcode == BUILT_IN_TM_STORE_LDOUBLE
434 || fcode == BUILT_IN_TM_STORE_M64
435 || fcode == BUILT_IN_TM_STORE_M128
436 || fcode == BUILT_IN_TM_STORE_M256);
438 return false;
441 /* Return true if FNDECL is BUILT_IN_TM_ABORT. */
443 static bool
444 is_tm_abort (tree fndecl)
446 return (fndecl
447 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
448 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
451 /* Build a GENERIC tree for a user abort. This is called by front ends
452 while transforming the __tm_abort statement. */
454 tree
455 build_tm_abort_call (location_t loc, bool is_outer)
457 return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
458 build_int_cst (integer_type_node,
459 AR_USERABORT
460 | (is_outer ? AR_OUTERABORT : 0)));
463 /* Common gateing function for several of the TM passes. */
465 static bool
466 gate_tm (void)
468 return flag_tm;
471 /* Map for aribtrary function replacement under TM, as created
472 by the tm_wrap attribute. */
474 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
475 htab_t tm_wrap_map;
477 void
478 record_tm_replacement (tree from, tree to)
480 struct tree_map **slot, *h;
482 /* Do not inline wrapper functions that will get replaced in the TM
483 pass.
485 Suppose you have foo() that will get replaced into tmfoo(). Make
486 sure the inliner doesn't try to outsmart us and inline foo()
487 before we get a chance to do the TM replacement. */
488 DECL_UNINLINABLE (from) = 1;
490 if (tm_wrap_map == NULL)
491 tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
493 h = ggc_alloc_tree_map ();
494 h->hash = htab_hash_pointer (from);
495 h->base.from = from;
496 h->to = to;
498 slot = (struct tree_map **)
499 htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
500 *slot = h;
503 /* Return a TM-aware replacement function for DECL. */
505 static tree
506 find_tm_replacement_function (tree fndecl)
508 if (tm_wrap_map)
510 struct tree_map *h, in;
512 in.base.from = fndecl;
513 in.hash = htab_hash_pointer (fndecl);
514 h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
515 if (h)
516 return h->to;
519 /* ??? We may well want TM versions of most of the common <string.h>
520 functions. For now, we've already these two defined. */
521 /* Adjust expand_call_tm() attributes as necessary for the cases
522 handled here: */
523 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
524 switch (DECL_FUNCTION_CODE (fndecl))
526 case BUILT_IN_MEMCPY:
527 return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
528 case BUILT_IN_MEMMOVE:
529 return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
530 case BUILT_IN_MEMSET:
531 return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
532 default:
533 return NULL;
536 return NULL;
539 /* When appropriate, record TM replacement for memory allocation functions.
541 FROM is the FNDECL to wrap. */
542 void
543 tm_malloc_replacement (tree from)
545 const char *str;
546 tree to;
548 if (TREE_CODE (from) != FUNCTION_DECL)
549 return;
551 /* If we have a previous replacement, the user must be explicitly
552 wrapping malloc/calloc/free. They better know what they're
553 doing... */
554 if (find_tm_replacement_function (from))
555 return;
557 str = IDENTIFIER_POINTER (DECL_NAME (from));
559 if (!strcmp (str, "malloc"))
560 to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
561 else if (!strcmp (str, "calloc"))
562 to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
563 else if (!strcmp (str, "free"))
564 to = builtin_decl_explicit (BUILT_IN_TM_FREE);
565 else
566 return;
568 TREE_NOTHROW (to) = 0;
570 record_tm_replacement (from, to);
573 /* Diagnostics for tm_safe functions/regions. Called by the front end
574 once we've lowered the function to high-gimple. */
576 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
577 Process exactly one statement. WI->INFO is set to non-null when in
578 the context of a tm_safe function, and null for a __transaction block. */
580 #define DIAG_TM_OUTER 1
581 #define DIAG_TM_SAFE 2
582 #define DIAG_TM_RELAXED 4
584 struct diagnose_tm
586 unsigned int summary_flags : 8;
587 unsigned int block_flags : 8;
588 unsigned int func_flags : 8;
589 unsigned int saw_volatile : 1;
590 gimple stmt;
593 /* Return true if T is a volatile variable of some kind. */
595 static bool
596 volatile_var_p (tree t)
598 return (SSA_VAR_P (t)
599 && TREE_THIS_VOLATILE (TREE_TYPE (t)));
602 /* Tree callback function for diagnose_tm pass. */
604 static tree
605 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
606 void *data)
608 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
609 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
611 if (volatile_var_p (*tp)
612 && d->block_flags & DIAG_TM_SAFE
613 && !d->saw_volatile)
615 d->saw_volatile = 1;
616 error_at (gimple_location (d->stmt),
617 "invalid volatile use of %qD inside transaction",
618 *tp);
621 return NULL_TREE;
624 static inline bool
625 is_tm_safe_or_pure (const_tree x)
627 return is_tm_safe (x) || is_tm_pure (x);
630 static tree
631 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
632 struct walk_stmt_info *wi)
634 gimple stmt = gsi_stmt (*gsi);
635 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
637 /* Save stmt for use in leaf analysis. */
638 d->stmt = stmt;
640 switch (gimple_code (stmt))
642 case GIMPLE_CALL:
644 tree fn = gimple_call_fn (stmt);
646 if ((d->summary_flags & DIAG_TM_OUTER) == 0
647 && is_tm_may_cancel_outer (fn))
648 error_at (gimple_location (stmt),
649 "%<transaction_may_cancel_outer%> function call not within"
650 " outer transaction or %<transaction_may_cancel_outer%>");
652 if (d->summary_flags & DIAG_TM_SAFE)
654 bool is_safe, direct_call_p;
655 tree replacement;
657 if (TREE_CODE (fn) == ADDR_EXPR
658 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
660 direct_call_p = true;
661 replacement = TREE_OPERAND (fn, 0);
662 replacement = find_tm_replacement_function (replacement);
663 if (replacement)
664 fn = replacement;
666 else
668 direct_call_p = false;
669 replacement = NULL_TREE;
672 if (is_tm_safe_or_pure (fn))
673 is_safe = true;
674 else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
676 /* A function explicitly marked transaction_callable as
677 opposed to transaction_safe is being defined to be
678 unsafe as part of its ABI, regardless of its contents. */
679 is_safe = false;
681 else if (direct_call_p)
683 if (IS_TYPE_OR_DECL_P (fn)
684 && flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
685 is_safe = true;
686 else if (replacement)
688 /* ??? At present we've been considering replacements
689 merely transaction_callable, and therefore might
690 enter irrevocable. The tm_wrap attribute has not
691 yet made it into the new language spec. */
692 is_safe = false;
694 else
696 /* ??? Diagnostics for unmarked direct calls moved into
697 the IPA pass. Section 3.2 of the spec details how
698 functions not marked should be considered "implicitly
699 safe" based on having examined the function body. */
700 is_safe = true;
703 else
705 /* An unmarked indirect call. Consider it unsafe even
706 though optimization may yet figure out how to inline. */
707 is_safe = false;
710 if (!is_safe)
712 if (TREE_CODE (fn) == ADDR_EXPR)
713 fn = TREE_OPERAND (fn, 0);
714 if (d->block_flags & DIAG_TM_SAFE)
716 if (direct_call_p)
717 error_at (gimple_location (stmt),
718 "unsafe function call %qD within "
719 "atomic transaction", fn);
720 else
722 if (!DECL_P (fn) || DECL_NAME (fn))
723 error_at (gimple_location (stmt),
724 "unsafe function call %qE within "
725 "atomic transaction", fn);
726 else
727 error_at (gimple_location (stmt),
728 "unsafe indirect function call within "
729 "atomic transaction");
732 else
734 if (direct_call_p)
735 error_at (gimple_location (stmt),
736 "unsafe function call %qD within "
737 "%<transaction_safe%> function", fn);
738 else
740 if (!DECL_P (fn) || DECL_NAME (fn))
741 error_at (gimple_location (stmt),
742 "unsafe function call %qE within "
743 "%<transaction_safe%> function", fn);
744 else
745 error_at (gimple_location (stmt),
746 "unsafe indirect function call within "
747 "%<transaction_safe%> function");
753 break;
755 case GIMPLE_ASM:
756 /* ??? We ought to come up with a way to add attributes to
757 asm statements, and then add "transaction_safe" to it.
758 Either that or get the language spec to resurrect __tm_waiver. */
759 if (d->block_flags & DIAG_TM_SAFE)
760 error_at (gimple_location (stmt),
761 "asm not allowed in atomic transaction");
762 else if (d->func_flags & DIAG_TM_SAFE)
763 error_at (gimple_location (stmt),
764 "asm not allowed in %<transaction_safe%> function");
765 break;
767 case GIMPLE_TRANSACTION:
769 unsigned char inner_flags = DIAG_TM_SAFE;
771 if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
773 if (d->block_flags & DIAG_TM_SAFE)
774 error_at (gimple_location (stmt),
775 "relaxed transaction in atomic transaction");
776 else if (d->func_flags & DIAG_TM_SAFE)
777 error_at (gimple_location (stmt),
778 "relaxed transaction in %<transaction_safe%> function");
779 inner_flags = DIAG_TM_RELAXED;
781 else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
783 if (d->block_flags)
784 error_at (gimple_location (stmt),
785 "outer transaction in transaction");
786 else if (d->func_flags & DIAG_TM_OUTER)
787 error_at (gimple_location (stmt),
788 "outer transaction in "
789 "%<transaction_may_cancel_outer%> function");
790 else if (d->func_flags & DIAG_TM_SAFE)
791 error_at (gimple_location (stmt),
792 "outer transaction in %<transaction_safe%> function");
793 inner_flags |= DIAG_TM_OUTER;
796 *handled_ops_p = true;
797 if (gimple_transaction_body (stmt))
799 struct walk_stmt_info wi_inner;
800 struct diagnose_tm d_inner;
802 memset (&d_inner, 0, sizeof (d_inner));
803 d_inner.func_flags = d->func_flags;
804 d_inner.block_flags = d->block_flags | inner_flags;
805 d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
807 memset (&wi_inner, 0, sizeof (wi_inner));
808 wi_inner.info = &d_inner;
810 walk_gimple_seq (gimple_transaction_body (stmt),
811 diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
814 break;
816 default:
817 break;
820 return NULL_TREE;
823 static unsigned int
824 diagnose_tm_blocks (void)
826 struct walk_stmt_info wi;
827 struct diagnose_tm d;
829 memset (&d, 0, sizeof (d));
830 if (is_tm_may_cancel_outer (current_function_decl))
831 d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
832 else if (is_tm_safe (current_function_decl))
833 d.func_flags = DIAG_TM_SAFE;
834 d.summary_flags = d.func_flags;
836 memset (&wi, 0, sizeof (wi));
837 wi.info = &d;
839 walk_gimple_seq (gimple_body (current_function_decl),
840 diagnose_tm_1, diagnose_tm_1_op, &wi);
842 return 0;
845 namespace {
847 const pass_data pass_data_diagnose_tm_blocks =
849 GIMPLE_PASS, /* type */
850 "*diagnose_tm_blocks", /* name */
851 OPTGROUP_NONE, /* optinfo_flags */
852 true, /* has_gate */
853 true, /* has_execute */
854 TV_TRANS_MEM, /* tv_id */
855 PROP_gimple_any, /* properties_required */
856 0, /* properties_provided */
857 0, /* properties_destroyed */
858 0, /* todo_flags_start */
859 0, /* todo_flags_finish */
862 class pass_diagnose_tm_blocks : public gimple_opt_pass
864 public:
865 pass_diagnose_tm_blocks (gcc::context *ctxt)
866 : gimple_opt_pass (pass_data_diagnose_tm_blocks, ctxt)
869 /* opt_pass methods: */
870 bool gate () { return gate_tm (); }
871 unsigned int execute () { return diagnose_tm_blocks (); }
873 }; // class pass_diagnose_tm_blocks
875 } // anon namespace
877 gimple_opt_pass *
878 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
880 return new pass_diagnose_tm_blocks (ctxt);
883 /* Instead of instrumenting thread private memory, we save the
884 addresses in a log which we later use to save/restore the addresses
885 upon transaction start/restart.
887 The log is keyed by address, where each element contains individual
888 statements among different code paths that perform the store.
890 This log is later used to generate either plain save/restore of the
891 addresses upon transaction start/restart, or calls to the ITM_L*
892 logging functions.
894 So for something like:
896 struct large { int x[1000]; };
897 struct large lala = { 0 };
898 __transaction {
899 lala.x[i] = 123;
903 We can either save/restore:
905 lala = { 0 };
906 trxn = _ITM_startTransaction ();
907 if (trxn & a_saveLiveVariables)
908 tmp_lala1 = lala.x[i];
909 else if (a & a_restoreLiveVariables)
910 lala.x[i] = tmp_lala1;
912 or use the logging functions:
914 lala = { 0 };
915 trxn = _ITM_startTransaction ();
916 _ITM_LU4 (&lala.x[i]);
918 Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
919 far up the dominator tree to shadow all of the writes to a given
920 location (thus reducing the total number of logging calls), but not
921 so high as to be called on a path that does not perform a
922 write. */
924 /* One individual log entry. We may have multiple statements for the
925 same location if neither dominate each other (on different
926 execution paths). */
927 typedef struct tm_log_entry
929 /* Address to save. */
930 tree addr;
931 /* Entry block for the transaction this address occurs in. */
932 basic_block entry_block;
933 /* Dominating statements the store occurs in. */
934 gimple_vec stmts;
935 /* Initially, while we are building the log, we place a nonzero
936 value here to mean that this address *will* be saved with a
937 save/restore sequence. Later, when generating the save sequence
938 we place the SSA temp generated here. */
939 tree save_var;
940 } *tm_log_entry_t;
943 /* Log entry hashtable helpers. */
945 struct log_entry_hasher
947 typedef tm_log_entry value_type;
948 typedef tm_log_entry compare_type;
949 static inline hashval_t hash (const value_type *);
950 static inline bool equal (const value_type *, const compare_type *);
951 static inline void remove (value_type *);
954 /* Htab support. Return hash value for a `tm_log_entry'. */
955 inline hashval_t
956 log_entry_hasher::hash (const value_type *log)
958 return iterative_hash_expr (log->addr, 0);
961 /* Htab support. Return true if two log entries are the same. */
962 inline bool
963 log_entry_hasher::equal (const value_type *log1, const compare_type *log2)
965 /* FIXME:
967 rth: I suggest that we get rid of the component refs etc.
968 I.e. resolve the reference to base + offset.
970 We may need to actually finish a merge with mainline for this,
971 since we'd like to be presented with Richi's MEM_REF_EXPRs more
972 often than not. But in the meantime your tm_log_entry could save
973 the results of get_inner_reference.
975 See: g++.dg/tm/pr46653.C
978 /* Special case plain equality because operand_equal_p() below will
979 return FALSE if the addresses are equal but they have
980 side-effects (e.g. a volatile address). */
981 if (log1->addr == log2->addr)
982 return true;
984 return operand_equal_p (log1->addr, log2->addr, 0);
987 /* Htab support. Free one tm_log_entry. */
988 inline void
989 log_entry_hasher::remove (value_type *lp)
991 lp->stmts.release ();
992 free (lp);
996 /* The actual log. */
997 static hash_table <log_entry_hasher> tm_log;
999 /* Addresses to log with a save/restore sequence. These should be in
1000 dominator order. */
1001 static vec<tree> tm_log_save_addresses;
1003 enum thread_memory_type
1005 mem_non_local = 0,
1006 mem_thread_local,
1007 mem_transaction_local,
1008 mem_max
1011 typedef struct tm_new_mem_map
1013 /* SSA_NAME being dereferenced. */
1014 tree val;
1015 enum thread_memory_type local_new_memory;
1016 } tm_new_mem_map_t;
1018 /* Hashtable helpers. */
1020 struct tm_mem_map_hasher : typed_free_remove <tm_new_mem_map_t>
1022 typedef tm_new_mem_map_t value_type;
1023 typedef tm_new_mem_map_t compare_type;
1024 static inline hashval_t hash (const value_type *);
1025 static inline bool equal (const value_type *, const compare_type *);
1028 inline hashval_t
1029 tm_mem_map_hasher::hash (const value_type *v)
1031 return (intptr_t)v->val >> 4;
1034 inline bool
1035 tm_mem_map_hasher::equal (const value_type *v, const compare_type *c)
1037 return v->val == c->val;
1040 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1041 of memory (malloc, alloc, etc). */
1042 static hash_table <tm_mem_map_hasher> tm_new_mem_hash;
1044 /* Initialize logging data structures. */
1045 static void
1046 tm_log_init (void)
1048 tm_log.create (10);
1049 tm_new_mem_hash.create (5);
1050 tm_log_save_addresses.create (5);
1053 /* Free logging data structures. */
1054 static void
1055 tm_log_delete (void)
1057 tm_log.dispose ();
1058 tm_new_mem_hash.dispose ();
1059 tm_log_save_addresses.release ();
1062 /* Return true if MEM is a transaction invariant memory for the TM
1063 region starting at REGION_ENTRY_BLOCK. */
1064 static bool
1065 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1067 if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1068 && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1070 basic_block def_bb;
1072 def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1073 return def_bb != region_entry_block
1074 && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1077 mem = strip_invariant_refs (mem);
1078 return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1081 /* Given an address ADDR in STMT, find it in the memory log or add it,
1082 making sure to keep only the addresses highest in the dominator
1083 tree.
1085 ENTRY_BLOCK is the entry_block for the transaction.
1087 If we find the address in the log, make sure it's either the same
1088 address, or an equivalent one that dominates ADDR.
1090 If we find the address, but neither ADDR dominates the found
1091 address, nor the found one dominates ADDR, we're on different
1092 execution paths. Add it.
1094 If known, ENTRY_BLOCK is the entry block for the region, otherwise
1095 NULL. */
1096 static void
1097 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1099 tm_log_entry **slot;
1100 struct tm_log_entry l, *lp;
1102 l.addr = addr;
1103 slot = tm_log.find_slot (&l, INSERT);
1104 if (!*slot)
1106 tree type = TREE_TYPE (addr);
1108 lp = XNEW (struct tm_log_entry);
1109 lp->addr = addr;
1110 *slot = lp;
1112 /* Small invariant addresses can be handled as save/restores. */
1113 if (entry_block
1114 && transaction_invariant_address_p (lp->addr, entry_block)
1115 && TYPE_SIZE_UNIT (type) != NULL
1116 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
1117 && ((HOST_WIDE_INT) tree_to_uhwi (TYPE_SIZE_UNIT (type))
1118 < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1119 /* We must be able to copy this type normally. I.e., no
1120 special constructors and the like. */
1121 && !TREE_ADDRESSABLE (type))
1123 lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1124 lp->stmts.create (0);
1125 lp->entry_block = entry_block;
1126 /* Save addresses separately in dominator order so we don't
1127 get confused by overlapping addresses in the save/restore
1128 sequence. */
1129 tm_log_save_addresses.safe_push (lp->addr);
1131 else
1133 /* Use the logging functions. */
1134 lp->stmts.create (5);
1135 lp->stmts.quick_push (stmt);
1136 lp->save_var = NULL;
1139 else
1141 size_t i;
1142 gimple oldstmt;
1144 lp = *slot;
1146 /* If we're generating a save/restore sequence, we don't care
1147 about statements. */
1148 if (lp->save_var)
1149 return;
1151 for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1153 if (stmt == oldstmt)
1154 return;
1155 /* We already have a store to the same address, higher up the
1156 dominator tree. Nothing to do. */
1157 if (dominated_by_p (CDI_DOMINATORS,
1158 gimple_bb (stmt), gimple_bb (oldstmt)))
1159 return;
1160 /* We should be processing blocks in dominator tree order. */
1161 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1162 gimple_bb (oldstmt), gimple_bb (stmt)));
1164 /* Store is on a different code path. */
1165 lp->stmts.safe_push (stmt);
1169 /* Gimplify the address of a TARGET_MEM_REF. Return the SSA_NAME
1170 result, insert the new statements before GSI. */
1172 static tree
1173 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1175 if (TREE_CODE (x) == TARGET_MEM_REF)
1176 x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1177 else
1178 x = build_fold_addr_expr (x);
1179 return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1182 /* Instrument one address with the logging functions.
1183 ADDR is the address to save.
1184 STMT is the statement before which to place it. */
1185 static void
1186 tm_log_emit_stmt (tree addr, gimple stmt)
1188 tree type = TREE_TYPE (addr);
1189 tree size = TYPE_SIZE_UNIT (type);
1190 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1191 gimple log;
1192 enum built_in_function code = BUILT_IN_TM_LOG;
1194 if (type == float_type_node)
1195 code = BUILT_IN_TM_LOG_FLOAT;
1196 else if (type == double_type_node)
1197 code = BUILT_IN_TM_LOG_DOUBLE;
1198 else if (type == long_double_type_node)
1199 code = BUILT_IN_TM_LOG_LDOUBLE;
1200 else if (tree_fits_uhwi_p (size))
1202 unsigned int n = tree_to_uhwi (size);
1203 switch (n)
1205 case 1:
1206 code = BUILT_IN_TM_LOG_1;
1207 break;
1208 case 2:
1209 code = BUILT_IN_TM_LOG_2;
1210 break;
1211 case 4:
1212 code = BUILT_IN_TM_LOG_4;
1213 break;
1214 case 8:
1215 code = BUILT_IN_TM_LOG_8;
1216 break;
1217 default:
1218 code = BUILT_IN_TM_LOG;
1219 if (TREE_CODE (type) == VECTOR_TYPE)
1221 if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1222 code = BUILT_IN_TM_LOG_M64;
1223 else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1224 code = BUILT_IN_TM_LOG_M128;
1225 else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1226 code = BUILT_IN_TM_LOG_M256;
1228 break;
1232 addr = gimplify_addr (&gsi, addr);
1233 if (code == BUILT_IN_TM_LOG)
1234 log = gimple_build_call (builtin_decl_explicit (code), 2, addr, size);
1235 else
1236 log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1237 gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1240 /* Go through the log and instrument address that must be instrumented
1241 with the logging functions. Leave the save/restore addresses for
1242 later. */
1243 static void
1244 tm_log_emit (void)
1246 hash_table <log_entry_hasher>::iterator hi;
1247 struct tm_log_entry *lp;
1249 FOR_EACH_HASH_TABLE_ELEMENT (tm_log, lp, tm_log_entry_t, hi)
1251 size_t i;
1252 gimple stmt;
1254 if (dump_file)
1256 fprintf (dump_file, "TM thread private mem logging: ");
1257 print_generic_expr (dump_file, lp->addr, 0);
1258 fprintf (dump_file, "\n");
1261 if (lp->save_var)
1263 if (dump_file)
1264 fprintf (dump_file, "DUMPING to variable\n");
1265 continue;
1267 else
1269 if (dump_file)
1270 fprintf (dump_file, "DUMPING with logging functions\n");
1271 for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1272 tm_log_emit_stmt (lp->addr, stmt);
1277 /* Emit the save sequence for the corresponding addresses in the log.
1278 ENTRY_BLOCK is the entry block for the transaction.
1279 BB is the basic block to insert the code in. */
1280 static void
1281 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1283 size_t i;
1284 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1285 gimple stmt;
1286 struct tm_log_entry l, *lp;
1288 for (i = 0; i < tm_log_save_addresses.length (); ++i)
1290 l.addr = tm_log_save_addresses[i];
1291 lp = *(tm_log.find_slot (&l, NO_INSERT));
1292 gcc_assert (lp->save_var != NULL);
1294 /* We only care about variables in the current transaction. */
1295 if (lp->entry_block != entry_block)
1296 continue;
1298 stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1300 /* Make sure we can create an SSA_NAME for this type. For
1301 instance, aggregates aren't allowed, in which case the system
1302 will create a VOP for us and everything will just work. */
1303 if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1305 lp->save_var = make_ssa_name (lp->save_var, stmt);
1306 gimple_assign_set_lhs (stmt, lp->save_var);
1309 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1313 /* Emit the restore sequence for the corresponding addresses in the log.
1314 ENTRY_BLOCK is the entry block for the transaction.
1315 BB is the basic block to insert the code in. */
1316 static void
1317 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1319 int i;
1320 struct tm_log_entry l, *lp;
1321 gimple_stmt_iterator gsi;
1322 gimple stmt;
1324 for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1326 l.addr = tm_log_save_addresses[i];
1327 lp = *(tm_log.find_slot (&l, NO_INSERT));
1328 gcc_assert (lp->save_var != NULL);
1330 /* We only care about variables in the current transaction. */
1331 if (lp->entry_block != entry_block)
1332 continue;
1334 /* Restores are in LIFO order from the saves in case we have
1335 overlaps. */
1336 gsi = gsi_start_bb (bb);
1338 stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1339 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1344 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1345 struct walk_stmt_info *);
1346 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1347 struct walk_stmt_info *);
1349 /* Evaluate an address X being dereferenced and determine if it
1350 originally points to a non aliased new chunk of memory (malloc,
1351 alloca, etc).
1353 Return MEM_THREAD_LOCAL if it points to a thread-local address.
1354 Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1355 Return MEM_NON_LOCAL otherwise.
1357 ENTRY_BLOCK is the entry block to the transaction containing the
1358 dereference of X. */
1359 static enum thread_memory_type
1360 thread_private_new_memory (basic_block entry_block, tree x)
1362 gimple stmt = NULL;
1363 enum tree_code code;
1364 tm_new_mem_map_t **slot;
1365 tm_new_mem_map_t elt, *elt_p;
1366 tree val = x;
1367 enum thread_memory_type retval = mem_transaction_local;
1369 if (!entry_block
1370 || TREE_CODE (x) != SSA_NAME
1371 /* Possible uninitialized use, or a function argument. In
1372 either case, we don't care. */
1373 || SSA_NAME_IS_DEFAULT_DEF (x))
1374 return mem_non_local;
1376 /* Look in cache first. */
1377 elt.val = x;
1378 slot = tm_new_mem_hash.find_slot (&elt, INSERT);
1379 elt_p = *slot;
1380 if (elt_p)
1381 return elt_p->local_new_memory;
1383 /* Optimistically assume the memory is transaction local during
1384 processing. This catches recursion into this variable. */
1385 *slot = elt_p = XNEW (tm_new_mem_map_t);
1386 elt_p->val = val;
1387 elt_p->local_new_memory = mem_transaction_local;
1389 /* Search DEF chain to find the original definition of this address. */
1392 if (ptr_deref_may_alias_global_p (x))
1394 /* Address escapes. This is not thread-private. */
1395 retval = mem_non_local;
1396 goto new_memory_ret;
1399 stmt = SSA_NAME_DEF_STMT (x);
1401 /* If the malloc call is outside the transaction, this is
1402 thread-local. */
1403 if (retval != mem_thread_local
1404 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1405 retval = mem_thread_local;
1407 if (is_gimple_assign (stmt))
1409 code = gimple_assign_rhs_code (stmt);
1410 /* x = foo ==> foo */
1411 if (code == SSA_NAME)
1412 x = gimple_assign_rhs1 (stmt);
1413 /* x = foo + n ==> foo */
1414 else if (code == POINTER_PLUS_EXPR)
1415 x = gimple_assign_rhs1 (stmt);
1416 /* x = (cast*) foo ==> foo */
1417 else if (code == VIEW_CONVERT_EXPR || code == NOP_EXPR)
1418 x = gimple_assign_rhs1 (stmt);
1419 /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1420 else if (code == COND_EXPR)
1422 tree op1 = gimple_assign_rhs2 (stmt);
1423 tree op2 = gimple_assign_rhs3 (stmt);
1424 enum thread_memory_type mem;
1425 retval = thread_private_new_memory (entry_block, op1);
1426 if (retval == mem_non_local)
1427 goto new_memory_ret;
1428 mem = thread_private_new_memory (entry_block, op2);
1429 retval = MIN (retval, mem);
1430 goto new_memory_ret;
1432 else
1434 retval = mem_non_local;
1435 goto new_memory_ret;
1438 else
1440 if (gimple_code (stmt) == GIMPLE_PHI)
1442 unsigned int i;
1443 enum thread_memory_type mem;
1444 tree phi_result = gimple_phi_result (stmt);
1446 /* If any of the ancestors are non-local, we are sure to
1447 be non-local. Otherwise we can avoid doing anything
1448 and inherit what has already been generated. */
1449 retval = mem_max;
1450 for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1452 tree op = PHI_ARG_DEF (stmt, i);
1454 /* Exclude self-assignment. */
1455 if (phi_result == op)
1456 continue;
1458 mem = thread_private_new_memory (entry_block, op);
1459 if (mem == mem_non_local)
1461 retval = mem;
1462 goto new_memory_ret;
1464 retval = MIN (retval, mem);
1466 goto new_memory_ret;
1468 break;
1471 while (TREE_CODE (x) == SSA_NAME);
1473 if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1474 /* Thread-local or transaction-local. */
1476 else
1477 retval = mem_non_local;
1479 new_memory_ret:
1480 elt_p->local_new_memory = retval;
1481 return retval;
1484 /* Determine whether X has to be instrumented using a read
1485 or write barrier.
1487 ENTRY_BLOCK is the entry block for the region where stmt resides
1488 in. NULL if unknown.
1490 STMT is the statement in which X occurs in. It is used for thread
1491 private memory instrumentation. If no TPM instrumentation is
1492 desired, STMT should be null. */
1493 static bool
1494 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1496 tree orig = x;
1497 while (handled_component_p (x))
1498 x = TREE_OPERAND (x, 0);
1500 switch (TREE_CODE (x))
1502 case INDIRECT_REF:
1503 case MEM_REF:
1505 enum thread_memory_type ret;
1507 ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1508 if (ret == mem_non_local)
1509 return true;
1510 if (stmt && ret == mem_thread_local)
1511 /* ?? Should we pass `orig', or the INDIRECT_REF X. ?? */
1512 tm_log_add (entry_block, orig, stmt);
1514 /* Transaction-locals require nothing at all. For malloc, a
1515 transaction restart frees the memory and we reallocate.
1516 For alloca, the stack pointer gets reset by the retry and
1517 we reallocate. */
1518 return false;
1521 case TARGET_MEM_REF:
1522 if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1523 return true;
1524 x = TREE_OPERAND (TMR_BASE (x), 0);
1525 if (TREE_CODE (x) == PARM_DECL)
1526 return false;
1527 gcc_assert (TREE_CODE (x) == VAR_DECL);
1528 /* FALLTHRU */
1530 case PARM_DECL:
1531 case RESULT_DECL:
1532 case VAR_DECL:
1533 if (DECL_BY_REFERENCE (x))
1535 /* ??? This value is a pointer, but aggregate_value_p has been
1536 jigged to return true which confuses needs_to_live_in_memory.
1537 This ought to be cleaned up generically.
1539 FIXME: Verify this still happens after the next mainline
1540 merge. Testcase ie g++.dg/tm/pr47554.C.
1542 return false;
1545 if (is_global_var (x))
1546 return !TREE_READONLY (x);
1547 if (/* FIXME: This condition should actually go below in the
1548 tm_log_add() call, however is_call_clobbered() depends on
1549 aliasing info which is not available during
1550 gimplification. Since requires_barrier() gets called
1551 during lower_sequence_tm/gimplification, leave the call
1552 to needs_to_live_in_memory until we eliminate
1553 lower_sequence_tm altogether. */
1554 needs_to_live_in_memory (x))
1555 return true;
1556 else
1558 /* For local memory that doesn't escape (aka thread private
1559 memory), we can either save the value at the beginning of
1560 the transaction and restore on restart, or call a tm
1561 function to dynamically save and restore on restart
1562 (ITM_L*). */
1563 if (stmt)
1564 tm_log_add (entry_block, orig, stmt);
1565 return false;
1568 default:
1569 return false;
1573 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1574 a transaction region. */
1576 static void
1577 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1579 gimple stmt = gsi_stmt (*gsi);
1581 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1582 *state |= GTMA_HAVE_LOAD;
1583 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1584 *state |= GTMA_HAVE_STORE;
1587 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction. */
1589 static void
1590 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1592 gimple stmt = gsi_stmt (*gsi);
1593 tree fn;
1595 if (is_tm_pure_call (stmt))
1596 return;
1598 /* Check if this call is a transaction abort. */
1599 fn = gimple_call_fndecl (stmt);
1600 if (is_tm_abort (fn))
1601 *state |= GTMA_HAVE_ABORT;
1603 /* Note that something may happen. */
1604 *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1607 /* Lower a GIMPLE_TRANSACTION statement. */
1609 static void
1610 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1612 gimple g, stmt = gsi_stmt (*gsi);
1613 unsigned int *outer_state = (unsigned int *) wi->info;
1614 unsigned int this_state = 0;
1615 struct walk_stmt_info this_wi;
1617 /* First, lower the body. The scanning that we do inside gives
1618 us some idea of what we're dealing with. */
1619 memset (&this_wi, 0, sizeof (this_wi));
1620 this_wi.info = (void *) &this_state;
1621 walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1622 lower_sequence_tm, NULL, &this_wi);
1624 /* If there was absolutely nothing transaction related inside the
1625 transaction, we may elide it. Likewise if this is a nested
1626 transaction and does not contain an abort. */
1627 if (this_state == 0
1628 || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1630 if (outer_state)
1631 *outer_state |= this_state;
1633 gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1634 GSI_SAME_STMT);
1635 gimple_transaction_set_body (stmt, NULL);
1637 gsi_remove (gsi, true);
1638 wi->removed_stmt = true;
1639 return;
1642 /* Wrap the body of the transaction in a try-finally node so that
1643 the commit call is always properly called. */
1644 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1645 if (flag_exceptions)
1647 tree ptr;
1648 gimple_seq n_seq, e_seq;
1650 n_seq = gimple_seq_alloc_with_stmt (g);
1651 e_seq = NULL;
1653 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1654 1, integer_zero_node);
1655 ptr = create_tmp_var (ptr_type_node, NULL);
1656 gimple_call_set_lhs (g, ptr);
1657 gimple_seq_add_stmt (&e_seq, g);
1659 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1660 1, ptr);
1661 gimple_seq_add_stmt (&e_seq, g);
1663 g = gimple_build_eh_else (n_seq, e_seq);
1666 g = gimple_build_try (gimple_transaction_body (stmt),
1667 gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1668 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1670 gimple_transaction_set_body (stmt, NULL);
1672 /* If the transaction calls abort or if this is an outer transaction,
1673 add an "over" label afterwards. */
1674 if ((this_state & (GTMA_HAVE_ABORT))
1675 || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1677 tree label = create_artificial_label (UNKNOWN_LOCATION);
1678 gimple_transaction_set_label (stmt, label);
1679 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1682 /* Record the set of operations found for use later. */
1683 this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1684 gimple_transaction_set_subcode (stmt, this_state);
1687 /* Iterate through the statements in the sequence, lowering them all
1688 as appropriate for being in a transaction. */
1690 static tree
1691 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1692 struct walk_stmt_info *wi)
1694 unsigned int *state = (unsigned int *) wi->info;
1695 gimple stmt = gsi_stmt (*gsi);
1697 *handled_ops_p = true;
1698 switch (gimple_code (stmt))
1700 case GIMPLE_ASSIGN:
1701 /* Only memory reads/writes need to be instrumented. */
1702 if (gimple_assign_single_p (stmt))
1703 examine_assign_tm (state, gsi);
1704 break;
1706 case GIMPLE_CALL:
1707 examine_call_tm (state, gsi);
1708 break;
1710 case GIMPLE_ASM:
1711 *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1712 break;
1714 case GIMPLE_TRANSACTION:
1715 lower_transaction (gsi, wi);
1716 break;
1718 default:
1719 *handled_ops_p = !gimple_has_substatements (stmt);
1720 break;
1723 return NULL_TREE;
1726 /* Iterate through the statements in the sequence, lowering them all
1727 as appropriate for being outside of a transaction. */
1729 static tree
1730 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1731 struct walk_stmt_info * wi)
1733 gimple stmt = gsi_stmt (*gsi);
1735 if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1737 *handled_ops_p = true;
1738 lower_transaction (gsi, wi);
1740 else
1741 *handled_ops_p = !gimple_has_substatements (stmt);
1743 return NULL_TREE;
1746 /* Main entry point for flattening GIMPLE_TRANSACTION constructs. After
1747 this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1748 been moved out, and all the data required for constructing a proper
1749 CFG has been recorded. */
1751 static unsigned int
1752 execute_lower_tm (void)
1754 struct walk_stmt_info wi;
1755 gimple_seq body;
1757 /* Transactional clones aren't created until a later pass. */
1758 gcc_assert (!decl_is_tm_clone (current_function_decl));
1760 body = gimple_body (current_function_decl);
1761 memset (&wi, 0, sizeof (wi));
1762 walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1763 gimple_set_body (current_function_decl, body);
1765 return 0;
1768 namespace {
1770 const pass_data pass_data_lower_tm =
1772 GIMPLE_PASS, /* type */
1773 "tmlower", /* name */
1774 OPTGROUP_NONE, /* optinfo_flags */
1775 true, /* has_gate */
1776 true, /* has_execute */
1777 TV_TRANS_MEM, /* tv_id */
1778 PROP_gimple_lcf, /* properties_required */
1779 0, /* properties_provided */
1780 0, /* properties_destroyed */
1781 0, /* todo_flags_start */
1782 0, /* todo_flags_finish */
1785 class pass_lower_tm : public gimple_opt_pass
1787 public:
1788 pass_lower_tm (gcc::context *ctxt)
1789 : gimple_opt_pass (pass_data_lower_tm, ctxt)
1792 /* opt_pass methods: */
1793 bool gate () { return gate_tm (); }
1794 unsigned int execute () { return execute_lower_tm (); }
1796 }; // class pass_lower_tm
1798 } // anon namespace
1800 gimple_opt_pass *
1801 make_pass_lower_tm (gcc::context *ctxt)
1803 return new pass_lower_tm (ctxt);
1806 /* Collect region information for each transaction. */
1808 struct tm_region
1810 /* Link to the next unnested transaction. */
1811 struct tm_region *next;
1813 /* Link to the next inner transaction. */
1814 struct tm_region *inner;
1816 /* Link to the next outer transaction. */
1817 struct tm_region *outer;
1819 /* The GIMPLE_TRANSACTION statement beginning this transaction.
1820 After TM_MARK, this gets replaced by a call to
1821 BUILT_IN_TM_START. */
1822 gimple transaction_stmt;
1824 /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1825 BUILT_IN_TM_START, this field is true if the transaction is an
1826 outer transaction. */
1827 bool original_transaction_was_outer;
1829 /* Return value from BUILT_IN_TM_START. */
1830 tree tm_state;
1832 /* The entry block to this region. This will always be the first
1833 block of the body of the transaction. */
1834 basic_block entry_block;
1836 /* The first block after an expanded call to _ITM_beginTransaction. */
1837 basic_block restart_block;
1839 /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1840 These blocks are still a part of the region (i.e., the border is
1841 inclusive). Note that this set is only complete for paths in the CFG
1842 starting at ENTRY_BLOCK, and that there is no exit block recorded for
1843 the edge to the "over" label. */
1844 bitmap exit_blocks;
1846 /* The set of all blocks that have an TM_IRREVOCABLE call. */
1847 bitmap irr_blocks;
1850 typedef struct tm_region *tm_region_p;
1852 /* True if there are pending edge statements to be committed for the
1853 current function being scanned in the tmmark pass. */
1854 bool pending_edge_inserts_p;
1856 static struct tm_region *all_tm_regions;
1857 static bitmap_obstack tm_obstack;
1860 /* A subroutine of tm_region_init. Record the existence of the
1861 GIMPLE_TRANSACTION statement in a tree of tm_region elements. */
1863 static struct tm_region *
1864 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1866 struct tm_region *region;
1868 region = (struct tm_region *)
1869 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1871 if (outer)
1873 region->next = outer->inner;
1874 outer->inner = region;
1876 else
1878 region->next = all_tm_regions;
1879 all_tm_regions = region;
1881 region->inner = NULL;
1882 region->outer = outer;
1884 region->transaction_stmt = stmt;
1885 region->original_transaction_was_outer = false;
1886 region->tm_state = NULL;
1888 /* There are either one or two edges out of the block containing
1889 the GIMPLE_TRANSACTION, one to the actual region and one to the
1890 "over" label if the region contains an abort. The former will
1891 always be the one marked FALLTHRU. */
1892 region->entry_block = FALLTHRU_EDGE (bb)->dest;
1894 region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1895 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1897 return region;
1900 /* A subroutine of tm_region_init. Record all the exit and
1901 irrevocable blocks in BB into the region's exit_blocks and
1902 irr_blocks bitmaps. Returns the new region being scanned. */
1904 static struct tm_region *
1905 tm_region_init_1 (struct tm_region *region, basic_block bb)
1907 gimple_stmt_iterator gsi;
1908 gimple g;
1910 if (!region
1911 || (!region->irr_blocks && !region->exit_blocks))
1912 return region;
1914 /* Check to see if this is the end of a region by seeing if it
1915 contains a call to __builtin_tm_commit{,_eh}. Note that the
1916 outermost region for DECL_IS_TM_CLONE need not collect this. */
1917 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1919 g = gsi_stmt (gsi);
1920 if (gimple_code (g) == GIMPLE_CALL)
1922 tree fn = gimple_call_fndecl (g);
1923 if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1925 if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1926 || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1927 && region->exit_blocks)
1929 bitmap_set_bit (region->exit_blocks, bb->index);
1930 region = region->outer;
1931 break;
1933 if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1934 bitmap_set_bit (region->irr_blocks, bb->index);
1938 return region;
1941 /* Collect all of the transaction regions within the current function
1942 and record them in ALL_TM_REGIONS. The REGION parameter may specify
1943 an "outermost" region for use by tm clones. */
1945 static void
1946 tm_region_init (struct tm_region *region)
1948 gimple g;
1949 edge_iterator ei;
1950 edge e;
1951 basic_block bb;
1952 auto_vec<basic_block> queue;
1953 bitmap visited_blocks = BITMAP_ALLOC (NULL);
1954 struct tm_region *old_region;
1955 auto_vec<tm_region_p> bb_regions;
1957 all_tm_regions = region;
1958 bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1960 /* We could store this information in bb->aux, but we may get called
1961 through get_all_tm_blocks() from another pass that may be already
1962 using bb->aux. */
1963 bb_regions.safe_grow_cleared (last_basic_block_for_fn (cfun));
1965 queue.safe_push (bb);
1966 bb_regions[bb->index] = region;
1969 bb = queue.pop ();
1970 region = bb_regions[bb->index];
1971 bb_regions[bb->index] = NULL;
1973 /* Record exit and irrevocable blocks. */
1974 region = tm_region_init_1 (region, bb);
1976 /* Check for the last statement in the block beginning a new region. */
1977 g = last_stmt (bb);
1978 old_region = region;
1979 if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1980 region = tm_region_init_0 (region, bb, g);
1982 /* Process subsequent blocks. */
1983 FOR_EACH_EDGE (e, ei, bb->succs)
1984 if (!bitmap_bit_p (visited_blocks, e->dest->index))
1986 bitmap_set_bit (visited_blocks, e->dest->index);
1987 queue.safe_push (e->dest);
1989 /* If the current block started a new region, make sure that only
1990 the entry block of the new region is associated with this region.
1991 Other successors are still part of the old region. */
1992 if (old_region != region && e->dest != region->entry_block)
1993 bb_regions[e->dest->index] = old_region;
1994 else
1995 bb_regions[e->dest->index] = region;
1998 while (!queue.is_empty ());
1999 BITMAP_FREE (visited_blocks);
2002 /* The "gate" function for all transactional memory expansion and optimization
2003 passes. We collect region information for each top-level transaction, and
2004 if we don't find any, we skip all of the TM passes. Each region will have
2005 all of the exit blocks recorded, and the originating statement. */
2007 static bool
2008 gate_tm_init (void)
2010 if (!flag_tm)
2011 return false;
2013 calculate_dominance_info (CDI_DOMINATORS);
2014 bitmap_obstack_initialize (&tm_obstack);
2016 /* If the function is a TM_CLONE, then the entire function is the region. */
2017 if (decl_is_tm_clone (current_function_decl))
2019 struct tm_region *region = (struct tm_region *)
2020 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
2021 memset (region, 0, sizeof (*region));
2022 region->entry_block = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
2023 /* For a clone, the entire function is the region. But even if
2024 we don't need to record any exit blocks, we may need to
2025 record irrevocable blocks. */
2026 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
2028 tm_region_init (region);
2030 else
2032 tm_region_init (NULL);
2034 /* If we didn't find any regions, cleanup and skip the whole tree
2035 of tm-related optimizations. */
2036 if (all_tm_regions == NULL)
2038 bitmap_obstack_release (&tm_obstack);
2039 return false;
2043 return true;
2046 namespace {
2048 const pass_data pass_data_tm_init =
2050 GIMPLE_PASS, /* type */
2051 "*tminit", /* name */
2052 OPTGROUP_NONE, /* optinfo_flags */
2053 true, /* has_gate */
2054 false, /* has_execute */
2055 TV_TRANS_MEM, /* tv_id */
2056 ( PROP_ssa | PROP_cfg ), /* properties_required */
2057 0, /* properties_provided */
2058 0, /* properties_destroyed */
2059 0, /* todo_flags_start */
2060 0, /* todo_flags_finish */
2063 class pass_tm_init : public gimple_opt_pass
2065 public:
2066 pass_tm_init (gcc::context *ctxt)
2067 : gimple_opt_pass (pass_data_tm_init, ctxt)
2070 /* opt_pass methods: */
2071 bool gate () { return gate_tm_init (); }
2073 }; // class pass_tm_init
2075 } // anon namespace
2077 gimple_opt_pass *
2078 make_pass_tm_init (gcc::context *ctxt)
2080 return new pass_tm_init (ctxt);
2083 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2084 represented by STATE. */
2086 static inline void
2087 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2089 if (region && region->transaction_stmt)
2091 flags |= gimple_transaction_subcode (region->transaction_stmt);
2092 gimple_transaction_set_subcode (region->transaction_stmt, flags);
2096 /* Construct a memory load in a transactional context. Return the
2097 gimple statement performing the load, or NULL if there is no
2098 TM_LOAD builtin of the appropriate size to do the load.
2100 LOC is the location to use for the new statement(s). */
2102 static gimple
2103 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2105 enum built_in_function code = END_BUILTINS;
2106 tree t, type = TREE_TYPE (rhs), decl;
2107 gimple gcall;
2109 if (type == float_type_node)
2110 code = BUILT_IN_TM_LOAD_FLOAT;
2111 else if (type == double_type_node)
2112 code = BUILT_IN_TM_LOAD_DOUBLE;
2113 else if (type == long_double_type_node)
2114 code = BUILT_IN_TM_LOAD_LDOUBLE;
2115 else if (TYPE_SIZE_UNIT (type) != NULL
2116 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2118 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2120 case 1:
2121 code = BUILT_IN_TM_LOAD_1;
2122 break;
2123 case 2:
2124 code = BUILT_IN_TM_LOAD_2;
2125 break;
2126 case 4:
2127 code = BUILT_IN_TM_LOAD_4;
2128 break;
2129 case 8:
2130 code = BUILT_IN_TM_LOAD_8;
2131 break;
2135 if (code == END_BUILTINS)
2137 decl = targetm.vectorize.builtin_tm_load (type);
2138 if (!decl)
2139 return NULL;
2141 else
2142 decl = builtin_decl_explicit (code);
2144 t = gimplify_addr (gsi, rhs);
2145 gcall = gimple_build_call (decl, 1, t);
2146 gimple_set_location (gcall, loc);
2148 t = TREE_TYPE (TREE_TYPE (decl));
2149 if (useless_type_conversion_p (type, t))
2151 gimple_call_set_lhs (gcall, lhs);
2152 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2154 else
2156 gimple g;
2157 tree temp;
2159 temp = create_tmp_reg (t, NULL);
2160 gimple_call_set_lhs (gcall, temp);
2161 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2163 t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2164 g = gimple_build_assign (lhs, t);
2165 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2168 return gcall;
2172 /* Similarly for storing TYPE in a transactional context. */
2174 static gimple
2175 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2177 enum built_in_function code = END_BUILTINS;
2178 tree t, fn, type = TREE_TYPE (rhs), simple_type;
2179 gimple gcall;
2181 if (type == float_type_node)
2182 code = BUILT_IN_TM_STORE_FLOAT;
2183 else if (type == double_type_node)
2184 code = BUILT_IN_TM_STORE_DOUBLE;
2185 else if (type == long_double_type_node)
2186 code = BUILT_IN_TM_STORE_LDOUBLE;
2187 else if (TYPE_SIZE_UNIT (type) != NULL
2188 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2190 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2192 case 1:
2193 code = BUILT_IN_TM_STORE_1;
2194 break;
2195 case 2:
2196 code = BUILT_IN_TM_STORE_2;
2197 break;
2198 case 4:
2199 code = BUILT_IN_TM_STORE_4;
2200 break;
2201 case 8:
2202 code = BUILT_IN_TM_STORE_8;
2203 break;
2207 if (code == END_BUILTINS)
2209 fn = targetm.vectorize.builtin_tm_store (type);
2210 if (!fn)
2211 return NULL;
2213 else
2214 fn = builtin_decl_explicit (code);
2216 simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2218 if (TREE_CODE (rhs) == CONSTRUCTOR)
2220 /* Handle the easy initialization to zero. */
2221 if (!CONSTRUCTOR_ELTS (rhs))
2222 rhs = build_int_cst (simple_type, 0);
2223 else
2225 /* ...otherwise punt to the caller and probably use
2226 BUILT_IN_TM_MEMMOVE, because we can't wrap a
2227 VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2228 valid gimple. */
2229 return NULL;
2232 else if (!useless_type_conversion_p (simple_type, type))
2234 gimple g;
2235 tree temp;
2237 temp = create_tmp_reg (simple_type, NULL);
2238 t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2239 g = gimple_build_assign (temp, t);
2240 gimple_set_location (g, loc);
2241 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2243 rhs = temp;
2246 t = gimplify_addr (gsi, lhs);
2247 gcall = gimple_build_call (fn, 2, t, rhs);
2248 gimple_set_location (gcall, loc);
2249 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2251 return gcall;
2255 /* Expand an assignment statement into transactional builtins. */
2257 static void
2258 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2260 gimple stmt = gsi_stmt (*gsi);
2261 location_t loc = gimple_location (stmt);
2262 tree lhs = gimple_assign_lhs (stmt);
2263 tree rhs = gimple_assign_rhs1 (stmt);
2264 bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2265 bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2266 gimple gcall = NULL;
2268 if (!load_p && !store_p)
2270 /* Add thread private addresses to log if applicable. */
2271 requires_barrier (region->entry_block, lhs, stmt);
2272 gsi_next (gsi);
2273 return;
2276 // Remove original load/store statement.
2277 gsi_remove (gsi, true);
2279 if (load_p && !store_p)
2281 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2282 gcall = build_tm_load (loc, lhs, rhs, gsi);
2284 else if (store_p && !load_p)
2286 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2287 gcall = build_tm_store (loc, lhs, rhs, gsi);
2289 if (!gcall)
2291 tree lhs_addr, rhs_addr, tmp;
2293 if (load_p)
2294 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2295 if (store_p)
2296 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2298 /* ??? Figure out if there's any possible overlap between the LHS
2299 and the RHS and if not, use MEMCPY. */
2301 if (load_p && is_gimple_reg (lhs))
2303 tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2304 lhs_addr = build_fold_addr_expr (tmp);
2306 else
2308 tmp = NULL_TREE;
2309 lhs_addr = gimplify_addr (gsi, lhs);
2311 rhs_addr = gimplify_addr (gsi, rhs);
2312 gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2313 3, lhs_addr, rhs_addr,
2314 TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2315 gimple_set_location (gcall, loc);
2316 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2318 if (tmp)
2320 gcall = gimple_build_assign (lhs, tmp);
2321 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2325 /* Now that we have the load/store in its instrumented form, add
2326 thread private addresses to the log if applicable. */
2327 if (!store_p)
2328 requires_barrier (region->entry_block, lhs, gcall);
2330 // The calls to build_tm_{store,load} above inserted the instrumented
2331 // call into the stream.
2332 // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2336 /* Expand a call statement as appropriate for a transaction. That is,
2337 either verify that the call does not affect the transaction, or
2338 redirect the call to a clone that handles transactions, or change
2339 the transaction state to IRREVOCABLE. Return true if the call is
2340 one of the builtins that end a transaction. */
2342 static bool
2343 expand_call_tm (struct tm_region *region,
2344 gimple_stmt_iterator *gsi)
2346 gimple stmt = gsi_stmt (*gsi);
2347 tree lhs = gimple_call_lhs (stmt);
2348 tree fn_decl;
2349 struct cgraph_node *node;
2350 bool retval = false;
2352 fn_decl = gimple_call_fndecl (stmt);
2354 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2355 || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2356 transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2357 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2358 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2360 if (is_tm_pure_call (stmt))
2361 return false;
2363 if (fn_decl)
2364 retval = is_tm_ending_fndecl (fn_decl);
2365 if (!retval)
2367 /* Assume all non-const/pure calls write to memory, except
2368 transaction ending builtins. */
2369 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2372 /* For indirect calls, we already generated a call into the runtime. */
2373 if (!fn_decl)
2375 tree fn = gimple_call_fn (stmt);
2377 /* We are guaranteed never to go irrevocable on a safe or pure
2378 call, and the pure call was handled above. */
2379 if (is_tm_safe (fn))
2380 return false;
2381 else
2382 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2384 return false;
2387 node = cgraph_get_node (fn_decl);
2388 /* All calls should have cgraph here. */
2389 if (!node)
2391 /* We can have a nodeless call here if some pass after IPA-tm
2392 added uninstrumented calls. For example, loop distribution
2393 can transform certain loop constructs into __builtin_mem*
2394 calls. In this case, see if we have a suitable TM
2395 replacement and fill in the gaps. */
2396 gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2397 enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2398 gcc_assert (code == BUILT_IN_MEMCPY
2399 || code == BUILT_IN_MEMMOVE
2400 || code == BUILT_IN_MEMSET);
2402 tree repl = find_tm_replacement_function (fn_decl);
2403 if (repl)
2405 gimple_call_set_fndecl (stmt, repl);
2406 update_stmt (stmt);
2407 node = cgraph_create_node (repl);
2408 node->local.tm_may_enter_irr = false;
2409 return expand_call_tm (region, gsi);
2411 gcc_unreachable ();
2413 if (node->local.tm_may_enter_irr)
2414 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2416 if (is_tm_abort (fn_decl))
2418 transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2419 return true;
2422 /* Instrument the store if needed.
2424 If the assignment happens inside the function call (return slot
2425 optimization), there is no instrumentation to be done, since
2426 the callee should have done the right thing. */
2427 if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2428 && !gimple_call_return_slot_opt_p (stmt))
2430 tree tmp = create_tmp_reg (TREE_TYPE (lhs), NULL);
2431 location_t loc = gimple_location (stmt);
2432 edge fallthru_edge = NULL;
2434 /* Remember if the call was going to throw. */
2435 if (stmt_can_throw_internal (stmt))
2437 edge_iterator ei;
2438 edge e;
2439 basic_block bb = gimple_bb (stmt);
2441 FOR_EACH_EDGE (e, ei, bb->succs)
2442 if (e->flags & EDGE_FALLTHRU)
2444 fallthru_edge = e;
2445 break;
2449 gimple_call_set_lhs (stmt, tmp);
2450 update_stmt (stmt);
2451 stmt = gimple_build_assign (lhs, tmp);
2452 gimple_set_location (stmt, loc);
2454 /* We cannot throw in the middle of a BB. If the call was going
2455 to throw, place the instrumentation on the fallthru edge, so
2456 the call remains the last statement in the block. */
2457 if (fallthru_edge)
2459 gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2460 gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2461 expand_assign_tm (region, &fallthru_gsi);
2462 gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2463 pending_edge_inserts_p = true;
2465 else
2467 gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2468 expand_assign_tm (region, gsi);
2471 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2474 return retval;
2478 /* Expand all statements in BB as appropriate for being inside
2479 a transaction. */
2481 static void
2482 expand_block_tm (struct tm_region *region, basic_block bb)
2484 gimple_stmt_iterator gsi;
2486 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2488 gimple stmt = gsi_stmt (gsi);
2489 switch (gimple_code (stmt))
2491 case GIMPLE_ASSIGN:
2492 /* Only memory reads/writes need to be instrumented. */
2493 if (gimple_assign_single_p (stmt)
2494 && !gimple_clobber_p (stmt))
2496 expand_assign_tm (region, &gsi);
2497 continue;
2499 break;
2501 case GIMPLE_CALL:
2502 if (expand_call_tm (region, &gsi))
2503 return;
2504 break;
2506 case GIMPLE_ASM:
2507 gcc_unreachable ();
2509 default:
2510 break;
2512 if (!gsi_end_p (gsi))
2513 gsi_next (&gsi);
2517 /* Return the list of basic-blocks in REGION.
2519 STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2520 following a TM_IRREVOCABLE call.
2522 INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2523 uninstrumented code path blocks in the list of basic blocks
2524 returned, false otherwise. */
2526 static vec<basic_block>
2527 get_tm_region_blocks (basic_block entry_block,
2528 bitmap exit_blocks,
2529 bitmap irr_blocks,
2530 bitmap all_region_blocks,
2531 bool stop_at_irrevocable_p,
2532 bool include_uninstrumented_p = true)
2534 vec<basic_block> bbs = vNULL;
2535 unsigned i;
2536 edge e;
2537 edge_iterator ei;
2538 bitmap visited_blocks = BITMAP_ALLOC (NULL);
2540 i = 0;
2541 bbs.safe_push (entry_block);
2542 bitmap_set_bit (visited_blocks, entry_block->index);
2546 basic_block bb = bbs[i++];
2548 if (exit_blocks &&
2549 bitmap_bit_p (exit_blocks, bb->index))
2550 continue;
2552 if (stop_at_irrevocable_p
2553 && irr_blocks
2554 && bitmap_bit_p (irr_blocks, bb->index))
2555 continue;
2557 FOR_EACH_EDGE (e, ei, bb->succs)
2558 if ((include_uninstrumented_p
2559 || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2560 && !bitmap_bit_p (visited_blocks, e->dest->index))
2562 bitmap_set_bit (visited_blocks, e->dest->index);
2563 bbs.safe_push (e->dest);
2566 while (i < bbs.length ());
2568 if (all_region_blocks)
2569 bitmap_ior_into (all_region_blocks, visited_blocks);
2571 BITMAP_FREE (visited_blocks);
2572 return bbs;
2575 // Callback data for collect_bb2reg.
2576 struct bb2reg_stuff
2578 vec<tm_region_p> *bb2reg;
2579 bool include_uninstrumented_p;
2582 // Callback for expand_regions, collect innermost region data for each bb.
2583 static void *
2584 collect_bb2reg (struct tm_region *region, void *data)
2586 struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2587 vec<tm_region_p> *bb2reg = stuff->bb2reg;
2588 vec<basic_block> queue;
2589 unsigned int i;
2590 basic_block bb;
2592 queue = get_tm_region_blocks (region->entry_block,
2593 region->exit_blocks,
2594 region->irr_blocks,
2595 NULL,
2596 /*stop_at_irr_p=*/true,
2597 stuff->include_uninstrumented_p);
2599 // We expect expand_region to perform a post-order traversal of the region
2600 // tree. Therefore the last region seen for any bb is the innermost.
2601 FOR_EACH_VEC_ELT (queue, i, bb)
2602 (*bb2reg)[bb->index] = region;
2604 queue.release ();
2605 return NULL;
2608 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2609 // which a basic block belongs. Note that we only consider the instrumented
2610 // code paths for the region; the uninstrumented code paths are ignored if
2611 // INCLUDE_UNINSTRUMENTED_P is false.
2613 // ??? This data is very similar to the bb_regions array that is collected
2614 // during tm_region_init. Or, rather, this data is similar to what could
2615 // be used within tm_region_init. The actual computation in tm_region_init
2616 // begins and ends with bb_regions entirely full of NULL pointers, due to
2617 // the way in which pointers are swapped in and out of the array.
2619 // ??? Our callers expect that blocks are not shared between transactions.
2620 // When the optimizers get too smart, and blocks are shared, then during
2621 // the tm_mark phase we'll add log entries to only one of the two transactions,
2622 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2623 // cycles. The symptom being SSA defs that do not dominate their uses.
2624 // Note that the optimizers were locally correct with their transformation,
2625 // as we have no info within the program that suggests that the blocks cannot
2626 // be shared.
2628 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2629 // only known instance of this block sharing.
2631 static vec<tm_region_p>
2632 get_bb_regions_instrumented (bool traverse_clones,
2633 bool include_uninstrumented_p)
2635 unsigned n = last_basic_block_for_fn (cfun);
2636 struct bb2reg_stuff stuff;
2637 vec<tm_region_p> ret;
2639 ret.create (n);
2640 ret.safe_grow_cleared (n);
2641 stuff.bb2reg = &ret;
2642 stuff.include_uninstrumented_p = include_uninstrumented_p;
2643 expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2645 return ret;
2648 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2649 transaction. */
2651 void
2652 compute_transaction_bits (void)
2654 struct tm_region *region;
2655 vec<basic_block> queue;
2656 unsigned int i;
2657 basic_block bb;
2659 /* ?? Perhaps we need to abstract gate_tm_init further, because we
2660 certainly don't need it to calculate CDI_DOMINATOR info. */
2661 gate_tm_init ();
2663 FOR_EACH_BB_FN (bb, cfun)
2664 bb->flags &= ~BB_IN_TRANSACTION;
2666 for (region = all_tm_regions; region; region = region->next)
2668 queue = get_tm_region_blocks (region->entry_block,
2669 region->exit_blocks,
2670 region->irr_blocks,
2671 NULL,
2672 /*stop_at_irr_p=*/true);
2673 for (i = 0; queue.iterate (i, &bb); ++i)
2674 bb->flags |= BB_IN_TRANSACTION;
2675 queue.release ();
2678 if (all_tm_regions)
2679 bitmap_obstack_release (&tm_obstack);
2682 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2683 call to BUILT_IN_TM_START. */
2685 static void *
2686 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2688 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2689 basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2690 tree tm_state = region->tm_state;
2691 tree tm_state_type = TREE_TYPE (tm_state);
2692 edge abort_edge = NULL;
2693 edge inst_edge = NULL;
2694 edge uninst_edge = NULL;
2695 edge fallthru_edge = NULL;
2697 // Identify the various successors of the transaction start.
2699 edge_iterator i;
2700 edge e;
2701 FOR_EACH_EDGE (e, i, transaction_bb->succs)
2703 if (e->flags & EDGE_TM_ABORT)
2704 abort_edge = e;
2705 else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2706 uninst_edge = e;
2707 else
2708 inst_edge = e;
2709 if (e->flags & EDGE_FALLTHRU)
2710 fallthru_edge = e;
2714 /* ??? There are plenty of bits here we're not computing. */
2716 int subcode = gimple_transaction_subcode (region->transaction_stmt);
2717 int flags = 0;
2718 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2719 flags |= PR_DOESGOIRREVOCABLE;
2720 if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2721 flags |= PR_HASNOIRREVOCABLE;
2722 /* If the transaction does not have an abort in lexical scope and is not
2723 marked as an outer transaction, then it will never abort. */
2724 if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2725 flags |= PR_HASNOABORT;
2726 if ((subcode & GTMA_HAVE_STORE) == 0)
2727 flags |= PR_READONLY;
2728 if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2729 flags |= PR_INSTRUMENTEDCODE;
2730 if (uninst_edge)
2731 flags |= PR_UNINSTRUMENTEDCODE;
2732 if (subcode & GTMA_IS_OUTER)
2733 region->original_transaction_was_outer = true;
2734 tree t = build_int_cst (tm_state_type, flags);
2735 gimple call = gimple_build_call (tm_start, 1, t);
2736 gimple_call_set_lhs (call, tm_state);
2737 gimple_set_location (call, gimple_location (region->transaction_stmt));
2739 // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2740 gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2741 gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2742 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2743 gsi_remove (&gsi, true);
2744 region->transaction_stmt = call;
2747 // Generate log saves.
2748 if (!tm_log_save_addresses.is_empty ())
2749 tm_log_emit_saves (region->entry_block, transaction_bb);
2751 // In the beginning, we've no tests to perform on transaction restart.
2752 // Note that after this point, transaction_bb becomes the "most recent
2753 // block containing tests for the transaction".
2754 region->restart_block = region->entry_block;
2756 // Generate log restores.
2757 if (!tm_log_save_addresses.is_empty ())
2759 basic_block test_bb = create_empty_bb (transaction_bb);
2760 basic_block code_bb = create_empty_bb (test_bb);
2761 basic_block join_bb = create_empty_bb (code_bb);
2762 if (current_loops && transaction_bb->loop_father)
2764 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2765 add_bb_to_loop (code_bb, transaction_bb->loop_father);
2766 add_bb_to_loop (join_bb, transaction_bb->loop_father);
2768 if (region->restart_block == region->entry_block)
2769 region->restart_block = test_bb;
2771 tree t1 = create_tmp_reg (tm_state_type, NULL);
2772 tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2773 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2774 tm_state, t2);
2775 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2776 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2778 t2 = build_int_cst (tm_state_type, 0);
2779 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2780 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2782 tm_log_emit_restores (region->entry_block, code_bb);
2784 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2785 edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2786 edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2787 redirect_edge_pred (fallthru_edge, join_bb);
2789 join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2790 join_bb->count = test_bb->count = transaction_bb->count;
2792 ei->probability = PROB_ALWAYS;
2793 et->probability = PROB_LIKELY;
2794 ef->probability = PROB_UNLIKELY;
2795 et->count = apply_probability (test_bb->count, et->probability);
2796 ef->count = apply_probability (test_bb->count, ef->probability);
2798 code_bb->count = et->count;
2799 code_bb->frequency = EDGE_FREQUENCY (et);
2801 transaction_bb = join_bb;
2804 // If we have an ABORT edge, create a test to perform the abort.
2805 if (abort_edge)
2807 basic_block test_bb = create_empty_bb (transaction_bb);
2808 if (current_loops && transaction_bb->loop_father)
2809 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2810 if (region->restart_block == region->entry_block)
2811 region->restart_block = test_bb;
2813 tree t1 = create_tmp_reg (tm_state_type, NULL);
2814 tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2815 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2816 tm_state, t2);
2817 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2818 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2820 t2 = build_int_cst (tm_state_type, 0);
2821 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2822 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2824 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2825 test_bb->frequency = transaction_bb->frequency;
2826 test_bb->count = transaction_bb->count;
2827 ei->probability = PROB_ALWAYS;
2829 // Not abort edge. If both are live, chose one at random as we'll
2830 // we'll be fixing that up below.
2831 redirect_edge_pred (fallthru_edge, test_bb);
2832 fallthru_edge->flags = EDGE_FALSE_VALUE;
2833 fallthru_edge->probability = PROB_VERY_LIKELY;
2834 fallthru_edge->count
2835 = apply_probability (test_bb->count, fallthru_edge->probability);
2837 // Abort/over edge.
2838 redirect_edge_pred (abort_edge, test_bb);
2839 abort_edge->flags = EDGE_TRUE_VALUE;
2840 abort_edge->probability = PROB_VERY_UNLIKELY;
2841 abort_edge->count
2842 = apply_probability (test_bb->count, abort_edge->probability);
2844 transaction_bb = test_bb;
2847 // If we have both instrumented and uninstrumented code paths, select one.
2848 if (inst_edge && uninst_edge)
2850 basic_block test_bb = create_empty_bb (transaction_bb);
2851 if (current_loops && transaction_bb->loop_father)
2852 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2853 if (region->restart_block == region->entry_block)
2854 region->restart_block = test_bb;
2856 tree t1 = create_tmp_reg (tm_state_type, NULL);
2857 tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2859 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2860 tm_state, t2);
2861 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2862 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2864 t2 = build_int_cst (tm_state_type, 0);
2865 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2866 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2868 // Create the edge into test_bb first, as we want to copy values
2869 // out of the fallthru edge.
2870 edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2871 e->probability = fallthru_edge->probability;
2872 test_bb->count = e->count = fallthru_edge->count;
2873 test_bb->frequency = EDGE_FREQUENCY (e);
2875 // Now update the edges to the inst/uninist implementations.
2876 // For now assume that the paths are equally likely. When using HTM,
2877 // we'll try the uninst path first and fallback to inst path if htm
2878 // buffers are exceeded. Without HTM we start with the inst path and
2879 // use the uninst path when falling back to serial mode.
2880 redirect_edge_pred (inst_edge, test_bb);
2881 inst_edge->flags = EDGE_FALSE_VALUE;
2882 inst_edge->probability = REG_BR_PROB_BASE / 2;
2883 inst_edge->count
2884 = apply_probability (test_bb->count, inst_edge->probability);
2886 redirect_edge_pred (uninst_edge, test_bb);
2887 uninst_edge->flags = EDGE_TRUE_VALUE;
2888 uninst_edge->probability = REG_BR_PROB_BASE / 2;
2889 uninst_edge->count
2890 = apply_probability (test_bb->count, uninst_edge->probability);
2893 // If we have no previous special cases, and we have PHIs at the beginning
2894 // of the atomic region, this means we have a loop at the beginning of the
2895 // atomic region that shares the first block. This can cause problems with
2896 // the transaction restart abnormal edges to be added in the tm_edges pass.
2897 // Solve this by adding a new empty block to receive the abnormal edges.
2898 if (region->restart_block == region->entry_block
2899 && phi_nodes (region->entry_block))
2901 basic_block empty_bb = create_empty_bb (transaction_bb);
2902 region->restart_block = empty_bb;
2903 if (current_loops && transaction_bb->loop_father)
2904 add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2906 redirect_edge_pred (fallthru_edge, empty_bb);
2907 make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2910 return NULL;
2913 /* Generate the temporary to be used for the return value of
2914 BUILT_IN_TM_START. */
2916 static void *
2917 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2919 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2920 region->tm_state =
2921 create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2923 // Reset the subcode, post optimizations. We'll fill this in
2924 // again as we process blocks.
2925 if (region->exit_blocks)
2927 unsigned int subcode
2928 = gimple_transaction_subcode (region->transaction_stmt);
2930 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2931 subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2932 | GTMA_MAY_ENTER_IRREVOCABLE
2933 | GTMA_HAS_NO_INSTRUMENTATION);
2934 else
2935 subcode &= GTMA_DECLARATION_MASK;
2936 gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2939 return NULL;
2942 // Propagate flags from inner transactions outwards.
2943 static void
2944 propagate_tm_flags_out (struct tm_region *region)
2946 if (region == NULL)
2947 return;
2948 propagate_tm_flags_out (region->inner);
2950 if (region->outer && region->outer->transaction_stmt)
2952 unsigned s = gimple_transaction_subcode (region->transaction_stmt);
2953 s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2954 | GTMA_MAY_ENTER_IRREVOCABLE);
2955 s |= gimple_transaction_subcode (region->outer->transaction_stmt);
2956 gimple_transaction_set_subcode (region->outer->transaction_stmt, s);
2959 propagate_tm_flags_out (region->next);
2962 /* Entry point to the MARK phase of TM expansion. Here we replace
2963 transactional memory statements with calls to builtins, and function
2964 calls with their transactional clones (if available). But we don't
2965 yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges. */
2967 static unsigned int
2968 execute_tm_mark (void)
2970 pending_edge_inserts_p = false;
2972 expand_regions (all_tm_regions, generate_tm_state, NULL,
2973 /*traverse_clones=*/true);
2975 tm_log_init ();
2977 vec<tm_region_p> bb_regions
2978 = get_bb_regions_instrumented (/*traverse_clones=*/true,
2979 /*include_uninstrumented_p=*/false);
2980 struct tm_region *r;
2981 unsigned i;
2983 // Expand memory operations into calls into the runtime.
2984 // This collects log entries as well.
2985 FOR_EACH_VEC_ELT (bb_regions, i, r)
2987 if (r != NULL)
2989 if (r->transaction_stmt)
2991 unsigned sub = gimple_transaction_subcode (r->transaction_stmt);
2993 /* If we're sure to go irrevocable, there won't be
2994 anything to expand, since the run-time will go
2995 irrevocable right away. */
2996 if (sub & GTMA_DOES_GO_IRREVOCABLE
2997 && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2998 continue;
3000 expand_block_tm (r, BASIC_BLOCK_FOR_FN (cfun, i));
3004 bb_regions.release ();
3006 // Propagate flags from inner transactions outwards.
3007 propagate_tm_flags_out (all_tm_regions);
3009 // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
3010 expand_regions (all_tm_regions, expand_transaction, NULL,
3011 /*traverse_clones=*/false);
3013 tm_log_emit ();
3014 tm_log_delete ();
3016 if (pending_edge_inserts_p)
3017 gsi_commit_edge_inserts ();
3018 free_dominance_info (CDI_DOMINATORS);
3019 return 0;
3022 namespace {
3024 const pass_data pass_data_tm_mark =
3026 GIMPLE_PASS, /* type */
3027 "tmmark", /* name */
3028 OPTGROUP_NONE, /* optinfo_flags */
3029 false, /* has_gate */
3030 true, /* has_execute */
3031 TV_TRANS_MEM, /* tv_id */
3032 ( PROP_ssa | PROP_cfg ), /* properties_required */
3033 0, /* properties_provided */
3034 0, /* properties_destroyed */
3035 0, /* todo_flags_start */
3036 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3039 class pass_tm_mark : public gimple_opt_pass
3041 public:
3042 pass_tm_mark (gcc::context *ctxt)
3043 : gimple_opt_pass (pass_data_tm_mark, ctxt)
3046 /* opt_pass methods: */
3047 unsigned int execute () { return execute_tm_mark (); }
3049 }; // class pass_tm_mark
3051 } // anon namespace
3053 gimple_opt_pass *
3054 make_pass_tm_mark (gcc::context *ctxt)
3056 return new pass_tm_mark (ctxt);
3060 /* Create an abnormal edge from STMT at iter, splitting the block
3061 as necessary. Adjust *PNEXT as needed for the split block. */
3063 static inline void
3064 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3065 gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3067 basic_block bb = gimple_bb (stmt);
3068 if (!gsi_one_before_end_p (iter))
3070 edge e = split_block (bb, stmt);
3071 *pnext = gsi_start_bb (e->dest);
3073 make_edge (bb, dest_bb, EDGE_ABNORMAL);
3075 // Record the need for the edge for the benefit of the rtl passes.
3076 if (cfun->gimple_df->tm_restart == NULL)
3077 cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
3078 struct_ptr_eq, ggc_free);
3080 struct tm_restart_node dummy;
3081 dummy.stmt = stmt;
3082 dummy.label_or_list = gimple_block_label (dest_bb);
3084 void **slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
3085 struct tm_restart_node *n = (struct tm_restart_node *) *slot;
3086 if (n == NULL)
3088 n = ggc_alloc_tm_restart_node ();
3089 *n = dummy;
3091 else
3093 tree old = n->label_or_list;
3094 if (TREE_CODE (old) == LABEL_DECL)
3095 old = tree_cons (NULL, old, NULL);
3096 n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3100 /* Split block BB as necessary for every builtin function we added, and
3101 wire up the abnormal back edges implied by the transaction restart. */
3103 static void
3104 expand_block_edges (struct tm_region *const region, basic_block bb)
3106 gimple_stmt_iterator gsi, next_gsi;
3108 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3110 gimple stmt = gsi_stmt (gsi);
3112 next_gsi = gsi;
3113 gsi_next (&next_gsi);
3115 // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3116 if (gimple_code (stmt) != GIMPLE_CALL
3117 || (gimple_call_flags (stmt) & ECF_TM_BUILTIN) == 0)
3118 continue;
3120 if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_TM_ABORT)
3122 // If we have a ``_transaction_cancel [[outer]]'', there is only
3123 // one abnormal edge: to the transaction marked OUTER.
3124 // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3125 // constant argument, which we can examine here. Users invoking
3126 // TM_ABORT directly get what they deserve.
3127 tree arg = gimple_call_arg (stmt, 0);
3128 if (TREE_CODE (arg) == INTEGER_CST
3129 && (TREE_INT_CST_LOW (arg) & AR_OUTERABORT) != 0
3130 && !decl_is_tm_clone (current_function_decl))
3132 // Find the GTMA_IS_OUTER transaction.
3133 for (struct tm_region *o = region; o; o = o->outer)
3134 if (o->original_transaction_was_outer)
3136 split_bb_make_tm_edge (stmt, o->restart_block,
3137 gsi, &next_gsi);
3138 break;
3141 // Otherwise, the front-end should have semantically checked
3142 // outer aborts, but in either case the target region is not
3143 // within this function.
3144 continue;
3147 // Non-outer, TM aborts have an abnormal edge to the inner-most
3148 // transaction, the one being aborted;
3149 split_bb_make_tm_edge (stmt, region->restart_block, gsi, &next_gsi);
3152 // All TM builtins have an abnormal edge to the outer-most transaction.
3153 // We never restart inner transactions. For tm clones, we know a-priori
3154 // that the outer-most transaction is outside the function.
3155 if (decl_is_tm_clone (current_function_decl))
3156 continue;
3158 if (cfun->gimple_df->tm_restart == NULL)
3159 cfun->gimple_df->tm_restart
3160 = htab_create_ggc (31, struct_ptr_hash, struct_ptr_eq, ggc_free);
3162 // All TM builtins have an abnormal edge to the outer-most transaction.
3163 // We never restart inner transactions.
3164 for (struct tm_region *o = region; o; o = o->outer)
3165 if (!o->outer)
3167 split_bb_make_tm_edge (stmt, o->restart_block, gsi, &next_gsi);
3168 break;
3171 // Delete any tail-call annotation that may have been added.
3172 // The tail-call pass may have mis-identified the commit as being
3173 // a candidate because we had not yet added this restart edge.
3174 gimple_call_set_tail (stmt, false);
3178 /* Entry point to the final expansion of transactional nodes. */
3180 static unsigned int
3181 execute_tm_edges (void)
3183 vec<tm_region_p> bb_regions
3184 = get_bb_regions_instrumented (/*traverse_clones=*/false,
3185 /*include_uninstrumented_p=*/true);
3186 struct tm_region *r;
3187 unsigned i;
3189 FOR_EACH_VEC_ELT (bb_regions, i, r)
3190 if (r != NULL)
3191 expand_block_edges (r, BASIC_BLOCK_FOR_FN (cfun, i));
3193 bb_regions.release ();
3195 /* We've got to release the dominance info now, to indicate that it
3196 must be rebuilt completely. Otherwise we'll crash trying to update
3197 the SSA web in the TODO section following this pass. */
3198 free_dominance_info (CDI_DOMINATORS);
3199 bitmap_obstack_release (&tm_obstack);
3200 all_tm_regions = NULL;
3202 return 0;
3205 namespace {
3207 const pass_data pass_data_tm_edges =
3209 GIMPLE_PASS, /* type */
3210 "tmedge", /* name */
3211 OPTGROUP_NONE, /* optinfo_flags */
3212 false, /* has_gate */
3213 true, /* has_execute */
3214 TV_TRANS_MEM, /* tv_id */
3215 ( PROP_ssa | PROP_cfg ), /* properties_required */
3216 0, /* properties_provided */
3217 0, /* properties_destroyed */
3218 0, /* todo_flags_start */
3219 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3222 class pass_tm_edges : public gimple_opt_pass
3224 public:
3225 pass_tm_edges (gcc::context *ctxt)
3226 : gimple_opt_pass (pass_data_tm_edges, ctxt)
3229 /* opt_pass methods: */
3230 unsigned int execute () { return execute_tm_edges (); }
3232 }; // class pass_tm_edges
3234 } // anon namespace
3236 gimple_opt_pass *
3237 make_pass_tm_edges (gcc::context *ctxt)
3239 return new pass_tm_edges (ctxt);
3242 /* Helper function for expand_regions. Expand REGION and recurse to
3243 the inner region. Call CALLBACK on each region. CALLBACK returns
3244 NULL to continue the traversal, otherwise a non-null value which
3245 this function will return as well. TRAVERSE_CLONES is true if we
3246 should traverse transactional clones. */
3248 static void *
3249 expand_regions_1 (struct tm_region *region,
3250 void *(*callback)(struct tm_region *, void *),
3251 void *data,
3252 bool traverse_clones)
3254 void *retval = NULL;
3255 if (region->exit_blocks
3256 || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3258 retval = callback (region, data);
3259 if (retval)
3260 return retval;
3262 if (region->inner)
3264 retval = expand_regions (region->inner, callback, data, traverse_clones);
3265 if (retval)
3266 return retval;
3268 return retval;
3271 /* Traverse the regions enclosed and including REGION. Execute
3272 CALLBACK for each region, passing DATA. CALLBACK returns NULL to
3273 continue the traversal, otherwise a non-null value which this
3274 function will return as well. TRAVERSE_CLONES is true if we should
3275 traverse transactional clones. */
3277 static void *
3278 expand_regions (struct tm_region *region,
3279 void *(*callback)(struct tm_region *, void *),
3280 void *data,
3281 bool traverse_clones)
3283 void *retval = NULL;
3284 while (region)
3286 retval = expand_regions_1 (region, callback, data, traverse_clones);
3287 if (retval)
3288 return retval;
3289 region = region->next;
3291 return retval;
3295 /* A unique TM memory operation. */
3296 typedef struct tm_memop
3298 /* Unique ID that all memory operations to the same location have. */
3299 unsigned int value_id;
3300 /* Address of load/store. */
3301 tree addr;
3302 } *tm_memop_t;
3304 /* TM memory operation hashtable helpers. */
3306 struct tm_memop_hasher : typed_free_remove <tm_memop>
3308 typedef tm_memop value_type;
3309 typedef tm_memop compare_type;
3310 static inline hashval_t hash (const value_type *);
3311 static inline bool equal (const value_type *, const compare_type *);
3314 /* Htab support. Return a hash value for a `tm_memop'. */
3315 inline hashval_t
3316 tm_memop_hasher::hash (const value_type *mem)
3318 tree addr = mem->addr;
3319 /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3320 actually done with operand_equal_p (see tm_memop_eq). */
3321 if (TREE_CODE (addr) == ADDR_EXPR)
3322 addr = TREE_OPERAND (addr, 0);
3323 return iterative_hash_expr (addr, 0);
3326 /* Htab support. Return true if two tm_memop's are the same. */
3327 inline bool
3328 tm_memop_hasher::equal (const value_type *mem1, const compare_type *mem2)
3330 return operand_equal_p (mem1->addr, mem2->addr, 0);
3333 /* Sets for solving data flow equations in the memory optimization pass. */
3334 struct tm_memopt_bitmaps
3336 /* Stores available to this BB upon entry. Basically, stores that
3337 dominate this BB. */
3338 bitmap store_avail_in;
3339 /* Stores available at the end of this BB. */
3340 bitmap store_avail_out;
3341 bitmap store_antic_in;
3342 bitmap store_antic_out;
3343 /* Reads available to this BB upon entry. Basically, reads that
3344 dominate this BB. */
3345 bitmap read_avail_in;
3346 /* Reads available at the end of this BB. */
3347 bitmap read_avail_out;
3348 /* Reads performed in this BB. */
3349 bitmap read_local;
3350 /* Writes performed in this BB. */
3351 bitmap store_local;
3353 /* Temporary storage for pass. */
3354 /* Is the current BB in the worklist? */
3355 bool avail_in_worklist_p;
3356 /* Have we visited this BB? */
3357 bool visited_p;
3360 static bitmap_obstack tm_memopt_obstack;
3362 /* Unique counter for TM loads and stores. Loads and stores of the
3363 same address get the same ID. */
3364 static unsigned int tm_memopt_value_id;
3365 static hash_table <tm_memop_hasher> tm_memopt_value_numbers;
3367 #define STORE_AVAIL_IN(BB) \
3368 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3369 #define STORE_AVAIL_OUT(BB) \
3370 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3371 #define STORE_ANTIC_IN(BB) \
3372 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3373 #define STORE_ANTIC_OUT(BB) \
3374 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3375 #define READ_AVAIL_IN(BB) \
3376 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3377 #define READ_AVAIL_OUT(BB) \
3378 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3379 #define READ_LOCAL(BB) \
3380 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3381 #define STORE_LOCAL(BB) \
3382 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3383 #define AVAIL_IN_WORKLIST_P(BB) \
3384 ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3385 #define BB_VISITED_P(BB) \
3386 ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3388 /* Given a TM load/store in STMT, return the value number for the address
3389 it accesses. */
3391 static unsigned int
3392 tm_memopt_value_number (gimple stmt, enum insert_option op)
3394 struct tm_memop tmpmem, *mem;
3395 tm_memop **slot;
3397 gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3398 tmpmem.addr = gimple_call_arg (stmt, 0);
3399 slot = tm_memopt_value_numbers.find_slot (&tmpmem, op);
3400 if (*slot)
3401 mem = *slot;
3402 else if (op == INSERT)
3404 mem = XNEW (struct tm_memop);
3405 *slot = mem;
3406 mem->value_id = tm_memopt_value_id++;
3407 mem->addr = tmpmem.addr;
3409 else
3410 gcc_unreachable ();
3411 return mem->value_id;
3414 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL. */
3416 static void
3417 tm_memopt_accumulate_memops (basic_block bb)
3419 gimple_stmt_iterator gsi;
3421 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3423 gimple stmt = gsi_stmt (gsi);
3424 bitmap bits;
3425 unsigned int loc;
3427 if (is_tm_store (stmt))
3428 bits = STORE_LOCAL (bb);
3429 else if (is_tm_load (stmt))
3430 bits = READ_LOCAL (bb);
3431 else
3432 continue;
3434 loc = tm_memopt_value_number (stmt, INSERT);
3435 bitmap_set_bit (bits, loc);
3436 if (dump_file)
3438 fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3439 is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3440 gimple_bb (stmt)->index);
3441 print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3442 fprintf (dump_file, "\n");
3447 /* Prettily dump one of the memopt sets. BITS is the bitmap to dump. */
3449 static void
3450 dump_tm_memopt_set (const char *set_name, bitmap bits)
3452 unsigned i;
3453 bitmap_iterator bi;
3454 const char *comma = "";
3456 fprintf (dump_file, "TM memopt: %s: [", set_name);
3457 EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3459 hash_table <tm_memop_hasher>::iterator hi;
3460 struct tm_memop *mem = NULL;
3462 /* Yeah, yeah, yeah. Whatever. This is just for debugging. */
3463 FOR_EACH_HASH_TABLE_ELEMENT (tm_memopt_value_numbers, mem, tm_memop_t, hi)
3464 if (mem->value_id == i)
3465 break;
3466 gcc_assert (mem->value_id == i);
3467 fprintf (dump_file, "%s", comma);
3468 comma = ", ";
3469 print_generic_expr (dump_file, mem->addr, 0);
3471 fprintf (dump_file, "]\n");
3474 /* Prettily dump all of the memopt sets in BLOCKS. */
3476 static void
3477 dump_tm_memopt_sets (vec<basic_block> blocks)
3479 size_t i;
3480 basic_block bb;
3482 for (i = 0; blocks.iterate (i, &bb); ++i)
3484 fprintf (dump_file, "------------BB %d---------\n", bb->index);
3485 dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3486 dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3487 dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3488 dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3489 dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3490 dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3494 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB. */
3496 static void
3497 tm_memopt_compute_avin (basic_block bb)
3499 edge e;
3500 unsigned ix;
3502 /* Seed with the AVOUT of any predecessor. */
3503 for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3505 e = EDGE_PRED (bb, ix);
3506 /* Make sure we have already visited this BB, and is thus
3507 initialized.
3509 If e->src->aux is NULL, this predecessor is actually on an
3510 enclosing transaction. We only care about the current
3511 transaction, so ignore it. */
3512 if (e->src->aux && BB_VISITED_P (e->src))
3514 bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3515 bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3516 break;
3520 for (; ix < EDGE_COUNT (bb->preds); ix++)
3522 e = EDGE_PRED (bb, ix);
3523 if (e->src->aux && BB_VISITED_P (e->src))
3525 bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3526 bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3530 BB_VISITED_P (bb) = true;
3533 /* Compute the STORE_ANTIC_IN for the basic block BB. */
3535 static void
3536 tm_memopt_compute_antin (basic_block bb)
3538 edge e;
3539 unsigned ix;
3541 /* Seed with the ANTIC_OUT of any successor. */
3542 for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3544 e = EDGE_SUCC (bb, ix);
3545 /* Make sure we have already visited this BB, and is thus
3546 initialized. */
3547 if (BB_VISITED_P (e->dest))
3549 bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3550 break;
3554 for (; ix < EDGE_COUNT (bb->succs); ix++)
3556 e = EDGE_SUCC (bb, ix);
3557 if (BB_VISITED_P (e->dest))
3558 bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3561 BB_VISITED_P (bb) = true;
3564 /* Compute the AVAIL sets for every basic block in BLOCKS.
3566 We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3568 AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3569 AVAIL_IN[bb] = intersect (AVAIL_OUT[predecessors])
3571 This is basically what we do in lcm's compute_available(), but here
3572 we calculate two sets of sets (one for STOREs and one for READs),
3573 and we work on a region instead of the entire CFG.
3575 REGION is the TM region.
3576 BLOCKS are the basic blocks in the region. */
3578 static void
3579 tm_memopt_compute_available (struct tm_region *region,
3580 vec<basic_block> blocks)
3582 edge e;
3583 basic_block *worklist, *qin, *qout, *qend, bb;
3584 unsigned int qlen, i;
3585 edge_iterator ei;
3586 bool changed;
3588 /* Allocate a worklist array/queue. Entries are only added to the
3589 list if they were not already on the list. So the size is
3590 bounded by the number of basic blocks in the region. */
3591 qlen = blocks.length () - 1;
3592 qin = qout = worklist =
3593 XNEWVEC (basic_block, qlen);
3595 /* Put every block in the region on the worklist. */
3596 for (i = 0; blocks.iterate (i, &bb); ++i)
3598 /* Seed AVAIL_OUT with the LOCAL set. */
3599 bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3600 bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3602 AVAIL_IN_WORKLIST_P (bb) = true;
3603 /* No need to insert the entry block, since it has an AVIN of
3604 null, and an AVOUT that has already been seeded in. */
3605 if (bb != region->entry_block)
3606 *qin++ = bb;
3609 /* The entry block has been initialized with the local sets. */
3610 BB_VISITED_P (region->entry_block) = true;
3612 qin = worklist;
3613 qend = &worklist[qlen];
3615 /* Iterate until the worklist is empty. */
3616 while (qlen)
3618 /* Take the first entry off the worklist. */
3619 bb = *qout++;
3620 qlen--;
3622 if (qout >= qend)
3623 qout = worklist;
3625 /* This block can be added to the worklist again if necessary. */
3626 AVAIL_IN_WORKLIST_P (bb) = false;
3627 tm_memopt_compute_avin (bb);
3629 /* Note: We do not add the LOCAL sets here because we already
3630 seeded the AVAIL_OUT sets with them. */
3631 changed = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3632 changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3633 if (changed
3634 && (region->exit_blocks == NULL
3635 || !bitmap_bit_p (region->exit_blocks, bb->index)))
3636 /* If the out state of this block changed, then we need to add
3637 its successors to the worklist if they are not already in. */
3638 FOR_EACH_EDGE (e, ei, bb->succs)
3639 if (!AVAIL_IN_WORKLIST_P (e->dest)
3640 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
3642 *qin++ = e->dest;
3643 AVAIL_IN_WORKLIST_P (e->dest) = true;
3644 qlen++;
3646 if (qin >= qend)
3647 qin = worklist;
3651 free (worklist);
3653 if (dump_file)
3654 dump_tm_memopt_sets (blocks);
3657 /* Compute ANTIC sets for every basic block in BLOCKS.
3659 We compute STORE_ANTIC_OUT as follows:
3661 STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3662 STORE_ANTIC_IN[bb] = intersect(STORE_ANTIC_OUT[successors])
3664 REGION is the TM region.
3665 BLOCKS are the basic blocks in the region. */
3667 static void
3668 tm_memopt_compute_antic (struct tm_region *region,
3669 vec<basic_block> blocks)
3671 edge e;
3672 basic_block *worklist, *qin, *qout, *qend, bb;
3673 unsigned int qlen;
3674 int i;
3675 edge_iterator ei;
3677 /* Allocate a worklist array/queue. Entries are only added to the
3678 list if they were not already on the list. So the size is
3679 bounded by the number of basic blocks in the region. */
3680 qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3682 for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3684 bb = blocks[i];
3686 /* Seed ANTIC_OUT with the LOCAL set. */
3687 bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3689 /* Put every block in the region on the worklist. */
3690 AVAIL_IN_WORKLIST_P (bb) = true;
3691 /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3692 and their ANTIC_OUT has already been seeded in. */
3693 if (region->exit_blocks
3694 && !bitmap_bit_p (region->exit_blocks, bb->index))
3696 qlen++;
3697 *qin++ = bb;
3701 /* The exit blocks have been initialized with the local sets. */
3702 if (region->exit_blocks)
3704 unsigned int i;
3705 bitmap_iterator bi;
3706 EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3707 BB_VISITED_P (BASIC_BLOCK_FOR_FN (cfun, i)) = true;
3710 qin = worklist;
3711 qend = &worklist[qlen];
3713 /* Iterate until the worklist is empty. */
3714 while (qlen)
3716 /* Take the first entry off the worklist. */
3717 bb = *qout++;
3718 qlen--;
3720 if (qout >= qend)
3721 qout = worklist;
3723 /* This block can be added to the worklist again if necessary. */
3724 AVAIL_IN_WORKLIST_P (bb) = false;
3725 tm_memopt_compute_antin (bb);
3727 /* Note: We do not add the LOCAL sets here because we already
3728 seeded the ANTIC_OUT sets with them. */
3729 if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3730 && bb != region->entry_block)
3731 /* If the out state of this block changed, then we need to add
3732 its predecessors to the worklist if they are not already in. */
3733 FOR_EACH_EDGE (e, ei, bb->preds)
3734 if (!AVAIL_IN_WORKLIST_P (e->src))
3736 *qin++ = e->src;
3737 AVAIL_IN_WORKLIST_P (e->src) = true;
3738 qlen++;
3740 if (qin >= qend)
3741 qin = worklist;
3745 free (worklist);
3747 if (dump_file)
3748 dump_tm_memopt_sets (blocks);
3751 /* Offsets of load variants from TM_LOAD. For example,
3752 BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3753 See gtm-builtins.def. */
3754 #define TRANSFORM_RAR 1
3755 #define TRANSFORM_RAW 2
3756 #define TRANSFORM_RFW 3
3757 /* Offsets of store variants from TM_STORE. */
3758 #define TRANSFORM_WAR 1
3759 #define TRANSFORM_WAW 2
3761 /* Inform about a load/store optimization. */
3763 static void
3764 dump_tm_memopt_transform (gimple stmt)
3766 if (dump_file)
3768 fprintf (dump_file, "TM memopt: transforming: ");
3769 print_gimple_stmt (dump_file, stmt, 0, 0);
3770 fprintf (dump_file, "\n");
3774 /* Perform a read/write optimization. Replaces the TM builtin in STMT
3775 by a builtin that is OFFSET entries down in the builtins table in
3776 gtm-builtins.def. */
3778 static void
3779 tm_memopt_transform_stmt (unsigned int offset,
3780 gimple stmt,
3781 gimple_stmt_iterator *gsi)
3783 tree fn = gimple_call_fn (stmt);
3784 gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3785 TREE_OPERAND (fn, 0)
3786 = builtin_decl_explicit ((enum built_in_function)
3787 (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3788 + offset));
3789 gimple_call_set_fn (stmt, fn);
3790 gsi_replace (gsi, stmt, true);
3791 dump_tm_memopt_transform (stmt);
3794 /* Perform the actual TM memory optimization transformations in the
3795 basic blocks in BLOCKS. */
3797 static void
3798 tm_memopt_transform_blocks (vec<basic_block> blocks)
3800 size_t i;
3801 basic_block bb;
3802 gimple_stmt_iterator gsi;
3804 for (i = 0; blocks.iterate (i, &bb); ++i)
3806 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3808 gimple stmt = gsi_stmt (gsi);
3809 bitmap read_avail = READ_AVAIL_IN (bb);
3810 bitmap store_avail = STORE_AVAIL_IN (bb);
3811 bitmap store_antic = STORE_ANTIC_OUT (bb);
3812 unsigned int loc;
3814 if (is_tm_simple_load (stmt))
3816 loc = tm_memopt_value_number (stmt, NO_INSERT);
3817 if (store_avail && bitmap_bit_p (store_avail, loc))
3818 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3819 else if (store_antic && bitmap_bit_p (store_antic, loc))
3821 tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3822 bitmap_set_bit (store_avail, loc);
3824 else if (read_avail && bitmap_bit_p (read_avail, loc))
3825 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3826 else
3827 bitmap_set_bit (read_avail, loc);
3829 else if (is_tm_simple_store (stmt))
3831 loc = tm_memopt_value_number (stmt, NO_INSERT);
3832 if (store_avail && bitmap_bit_p (store_avail, loc))
3833 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3834 else
3836 if (read_avail && bitmap_bit_p (read_avail, loc))
3837 tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3838 bitmap_set_bit (store_avail, loc);
3845 /* Return a new set of bitmaps for a BB. */
3847 static struct tm_memopt_bitmaps *
3848 tm_memopt_init_sets (void)
3850 struct tm_memopt_bitmaps *b
3851 = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3852 b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3853 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3854 b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3855 b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3856 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3857 b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3858 b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3859 b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3860 b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3861 return b;
3864 /* Free sets computed for each BB. */
3866 static void
3867 tm_memopt_free_sets (vec<basic_block> blocks)
3869 size_t i;
3870 basic_block bb;
3872 for (i = 0; blocks.iterate (i, &bb); ++i)
3873 bb->aux = NULL;
3876 /* Clear the visited bit for every basic block in BLOCKS. */
3878 static void
3879 tm_memopt_clear_visited (vec<basic_block> blocks)
3881 size_t i;
3882 basic_block bb;
3884 for (i = 0; blocks.iterate (i, &bb); ++i)
3885 BB_VISITED_P (bb) = false;
3888 /* Replace TM load/stores with hints for the runtime. We handle
3889 things like read-after-write, write-after-read, read-after-read,
3890 read-for-write, etc. */
3892 static unsigned int
3893 execute_tm_memopt (void)
3895 struct tm_region *region;
3896 vec<basic_block> bbs;
3898 tm_memopt_value_id = 0;
3899 tm_memopt_value_numbers.create (10);
3901 for (region = all_tm_regions; region; region = region->next)
3903 /* All the TM stores/loads in the current region. */
3904 size_t i;
3905 basic_block bb;
3907 bitmap_obstack_initialize (&tm_memopt_obstack);
3909 /* Save all BBs for the current region. */
3910 bbs = get_tm_region_blocks (region->entry_block,
3911 region->exit_blocks,
3912 region->irr_blocks,
3913 NULL,
3914 false);
3916 /* Collect all the memory operations. */
3917 for (i = 0; bbs.iterate (i, &bb); ++i)
3919 bb->aux = tm_memopt_init_sets ();
3920 tm_memopt_accumulate_memops (bb);
3923 /* Solve data flow equations and transform each block accordingly. */
3924 tm_memopt_clear_visited (bbs);
3925 tm_memopt_compute_available (region, bbs);
3926 tm_memopt_clear_visited (bbs);
3927 tm_memopt_compute_antic (region, bbs);
3928 tm_memopt_transform_blocks (bbs);
3930 tm_memopt_free_sets (bbs);
3931 bbs.release ();
3932 bitmap_obstack_release (&tm_memopt_obstack);
3933 tm_memopt_value_numbers.empty ();
3936 tm_memopt_value_numbers.dispose ();
3937 return 0;
3940 static bool
3941 gate_tm_memopt (void)
3943 return flag_tm && optimize > 0;
3946 namespace {
3948 const pass_data pass_data_tm_memopt =
3950 GIMPLE_PASS, /* type */
3951 "tmmemopt", /* name */
3952 OPTGROUP_NONE, /* optinfo_flags */
3953 true, /* has_gate */
3954 true, /* has_execute */
3955 TV_TRANS_MEM, /* tv_id */
3956 ( PROP_ssa | PROP_cfg ), /* properties_required */
3957 0, /* properties_provided */
3958 0, /* properties_destroyed */
3959 0, /* todo_flags_start */
3960 0, /* todo_flags_finish */
3963 class pass_tm_memopt : public gimple_opt_pass
3965 public:
3966 pass_tm_memopt (gcc::context *ctxt)
3967 : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3970 /* opt_pass methods: */
3971 bool gate () { return gate_tm_memopt (); }
3972 unsigned int execute () { return execute_tm_memopt (); }
3974 }; // class pass_tm_memopt
3976 } // anon namespace
3978 gimple_opt_pass *
3979 make_pass_tm_memopt (gcc::context *ctxt)
3981 return new pass_tm_memopt (ctxt);
3985 /* Interprocedual analysis for the creation of transactional clones.
3986 The aim of this pass is to find which functions are referenced in
3987 a non-irrevocable transaction context, and for those over which
3988 we have control (or user directive), create a version of the
3989 function which uses only the transactional interface to reference
3990 protected memories. This analysis proceeds in several steps:
3992 (1) Collect the set of all possible transactional clones:
3994 (a) For all local public functions marked tm_callable, push
3995 it onto the tm_callee queue.
3997 (b) For all local functions, scan for calls in transaction blocks.
3998 Push the caller and callee onto the tm_caller and tm_callee
3999 queues. Count the number of callers for each callee.
4001 (c) For each local function on the callee list, assume we will
4002 create a transactional clone. Push *all* calls onto the
4003 callee queues; count the number of clone callers separately
4004 to the number of original callers.
4006 (2) Propagate irrevocable status up the dominator tree:
4008 (a) Any external function on the callee list that is not marked
4009 tm_callable is irrevocable. Push all callers of such onto
4010 a worklist.
4012 (b) For each function on the worklist, mark each block that
4013 contains an irrevocable call. Use the AND operator to
4014 propagate that mark up the dominator tree.
4016 (c) If we reach the entry block for a possible transactional
4017 clone, then the transactional clone is irrevocable, and
4018 we should not create the clone after all. Push all
4019 callers onto the worklist.
4021 (d) Place tm_irrevocable calls at the beginning of the relevant
4022 blocks. Special case here is the entry block for the entire
4023 transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
4024 the library to begin the region in serial mode. Decrement
4025 the call count for all callees in the irrevocable region.
4027 (3) Create the transactional clones:
4029 Any tm_callee that still has a non-zero call count is cloned.
4032 /* This structure is stored in the AUX field of each cgraph_node. */
4033 struct tm_ipa_cg_data
4035 /* The clone of the function that got created. */
4036 struct cgraph_node *clone;
4038 /* The tm regions in the normal function. */
4039 struct tm_region *all_tm_regions;
4041 /* The blocks of the normal/clone functions that contain irrevocable
4042 calls, or blocks that are post-dominated by irrevocable calls. */
4043 bitmap irrevocable_blocks_normal;
4044 bitmap irrevocable_blocks_clone;
4046 /* The blocks of the normal function that are involved in transactions. */
4047 bitmap transaction_blocks_normal;
4049 /* The number of callers to the transactional clone of this function
4050 from normal and transactional clones respectively. */
4051 unsigned tm_callers_normal;
4052 unsigned tm_callers_clone;
4054 /* True if all calls to this function's transactional clone
4055 are irrevocable. Also automatically true if the function
4056 has no transactional clone. */
4057 bool is_irrevocable;
4059 /* Flags indicating the presence of this function in various queues. */
4060 bool in_callee_queue;
4061 bool in_worklist;
4063 /* Flags indicating the kind of scan desired while in the worklist. */
4064 bool want_irr_scan_normal;
4067 typedef vec<cgraph_node_ptr> cgraph_node_queue;
4069 /* Return the ipa data associated with NODE, allocating zeroed memory
4070 if necessary. TRAVERSE_ALIASES is true if we must traverse aliases
4071 and set *NODE accordingly. */
4073 static struct tm_ipa_cg_data *
4074 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4076 struct tm_ipa_cg_data *d;
4078 if (traverse_aliases && (*node)->alias)
4079 *node = cgraph_alias_target (*node);
4081 d = (struct tm_ipa_cg_data *) (*node)->aux;
4083 if (d == NULL)
4085 d = (struct tm_ipa_cg_data *)
4086 obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4087 (*node)->aux = (void *) d;
4088 memset (d, 0, sizeof (*d));
4091 return d;
4094 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4095 it is already present. */
4097 static void
4098 maybe_push_queue (struct cgraph_node *node,
4099 cgraph_node_queue *queue_p, bool *in_queue_p)
4101 if (!*in_queue_p)
4103 *in_queue_p = true;
4104 queue_p->safe_push (node);
4108 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4109 code path. QUEUE are the basic blocks inside the transaction
4110 represented in REGION.
4112 Later in split_code_paths() we will add the conditional to choose
4113 between the two alternatives. */
4115 static void
4116 ipa_uninstrument_transaction (struct tm_region *region,
4117 vec<basic_block> queue)
4119 gimple transaction = region->transaction_stmt;
4120 basic_block transaction_bb = gimple_bb (transaction);
4121 int n = queue.length ();
4122 basic_block *new_bbs = XNEWVEC (basic_block, n);
4124 copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4125 true);
4126 edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4127 add_phi_args_after_copy (new_bbs, n, e);
4129 // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4130 // a) EDGE_FALLTHRU into the transaction
4131 // b) EDGE_TM_ABORT out of the transaction
4132 // c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4134 free (new_bbs);
4137 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4138 Queue all callees within block BB. */
4140 static void
4141 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4142 basic_block bb, bool for_clone)
4144 gimple_stmt_iterator gsi;
4146 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4148 gimple stmt = gsi_stmt (gsi);
4149 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4151 tree fndecl = gimple_call_fndecl (stmt);
4152 if (fndecl)
4154 struct tm_ipa_cg_data *d;
4155 unsigned *pcallers;
4156 struct cgraph_node *node;
4158 if (is_tm_ending_fndecl (fndecl))
4159 continue;
4160 if (find_tm_replacement_function (fndecl))
4161 continue;
4163 node = cgraph_get_node (fndecl);
4164 gcc_assert (node != NULL);
4165 d = get_cg_data (&node, true);
4167 pcallers = (for_clone ? &d->tm_callers_clone
4168 : &d->tm_callers_normal);
4169 *pcallers += 1;
4171 maybe_push_queue (node, callees_p, &d->in_callee_queue);
4177 /* Scan all calls in NODE that are within a transaction region,
4178 and push the resulting nodes into the callee queue. */
4180 static void
4181 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4182 cgraph_node_queue *callees_p)
4184 struct tm_region *r;
4186 d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4187 d->all_tm_regions = all_tm_regions;
4189 for (r = all_tm_regions; r; r = r->next)
4191 vec<basic_block> bbs;
4192 basic_block bb;
4193 unsigned i;
4195 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4196 d->transaction_blocks_normal, false);
4198 // Generate the uninstrumented code path for this transaction.
4199 ipa_uninstrument_transaction (r, bbs);
4201 FOR_EACH_VEC_ELT (bbs, i, bb)
4202 ipa_tm_scan_calls_block (callees_p, bb, false);
4204 bbs.release ();
4207 // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4208 // copying them, rather than forcing us to do this externally.
4209 rebuild_cgraph_edges ();
4211 // ??? In ipa_uninstrument_transaction we don't try to update dominators
4212 // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4213 // Instead, just release dominators here so update_ssa recomputes them.
4214 free_dominance_info (CDI_DOMINATORS);
4216 // When building the uninstrumented code path, copy_bbs will have invoked
4217 // create_new_def_for starting an "ssa update context". There is only one
4218 // instance of this context, so resolve ssa updates before moving on to
4219 // the next function.
4220 update_ssa (TODO_update_ssa);
4223 /* Scan all calls in NODE as if this is the transactional clone,
4224 and push the destinations into the callee queue. */
4226 static void
4227 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4228 cgraph_node_queue *callees_p)
4230 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
4231 basic_block bb;
4233 FOR_EACH_BB_FN (bb, fn)
4234 ipa_tm_scan_calls_block (callees_p, bb, true);
4237 /* The function NODE has been detected to be irrevocable. Push all
4238 of its callers onto WORKLIST for the purpose of re-scanning them. */
4240 static void
4241 ipa_tm_note_irrevocable (struct cgraph_node *node,
4242 cgraph_node_queue *worklist_p)
4244 struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4245 struct cgraph_edge *e;
4247 d->is_irrevocable = true;
4249 for (e = node->callers; e ; e = e->next_caller)
4251 basic_block bb;
4252 struct cgraph_node *caller;
4254 /* Don't examine recursive calls. */
4255 if (e->caller == node)
4256 continue;
4257 /* Even if we think we can go irrevocable, believe the user
4258 above all. */
4259 if (is_tm_safe_or_pure (e->caller->decl))
4260 continue;
4262 caller = e->caller;
4263 d = get_cg_data (&caller, true);
4265 /* Check if the callee is in a transactional region. If so,
4266 schedule the function for normal re-scan as well. */
4267 bb = gimple_bb (e->call_stmt);
4268 gcc_assert (bb != NULL);
4269 if (d->transaction_blocks_normal
4270 && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4271 d->want_irr_scan_normal = true;
4273 maybe_push_queue (caller, worklist_p, &d->in_worklist);
4277 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4278 within the block is irrevocable. */
4280 static bool
4281 ipa_tm_scan_irr_block (basic_block bb)
4283 gimple_stmt_iterator gsi;
4284 tree fn;
4286 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4288 gimple stmt = gsi_stmt (gsi);
4289 switch (gimple_code (stmt))
4291 case GIMPLE_ASSIGN:
4292 if (gimple_assign_single_p (stmt))
4294 tree lhs = gimple_assign_lhs (stmt);
4295 tree rhs = gimple_assign_rhs1 (stmt);
4296 if (volatile_var_p (lhs) || volatile_var_p (rhs))
4297 return true;
4299 break;
4301 case GIMPLE_CALL:
4303 tree lhs = gimple_call_lhs (stmt);
4304 if (lhs && volatile_var_p (lhs))
4305 return true;
4307 if (is_tm_pure_call (stmt))
4308 break;
4310 fn = gimple_call_fn (stmt);
4312 /* Functions with the attribute are by definition irrevocable. */
4313 if (is_tm_irrevocable (fn))
4314 return true;
4316 /* For direct function calls, go ahead and check for replacement
4317 functions, or transitive irrevocable functions. For indirect
4318 functions, we'll ask the runtime. */
4319 if (TREE_CODE (fn) == ADDR_EXPR)
4321 struct tm_ipa_cg_data *d;
4322 struct cgraph_node *node;
4324 fn = TREE_OPERAND (fn, 0);
4325 if (is_tm_ending_fndecl (fn))
4326 break;
4327 if (find_tm_replacement_function (fn))
4328 break;
4330 node = cgraph_get_node (fn);
4331 d = get_cg_data (&node, true);
4333 /* Return true if irrevocable, but above all, believe
4334 the user. */
4335 if (d->is_irrevocable
4336 && !is_tm_safe_or_pure (fn))
4337 return true;
4339 break;
4342 case GIMPLE_ASM:
4343 /* ??? The Approved Method of indicating that an inline
4344 assembly statement is not relevant to the transaction
4345 is to wrap it in a __tm_waiver block. This is not
4346 yet implemented, so we can't check for it. */
4347 if (is_tm_safe (current_function_decl))
4349 tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4350 SET_EXPR_LOCATION (t, gimple_location (stmt));
4351 error ("%Kasm not allowed in %<transaction_safe%> function", t);
4353 return true;
4355 default:
4356 break;
4360 return false;
4363 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4364 for new irrevocable blocks, marking them in NEW_IRR. Don't bother
4365 scanning past OLD_IRR or EXIT_BLOCKS. */
4367 static bool
4368 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4369 bitmap old_irr, bitmap exit_blocks)
4371 bool any_new_irr = false;
4372 edge e;
4373 edge_iterator ei;
4374 bitmap visited_blocks = BITMAP_ALLOC (NULL);
4378 basic_block bb = pqueue->pop ();
4380 /* Don't re-scan blocks we know already are irrevocable. */
4381 if (old_irr && bitmap_bit_p (old_irr, bb->index))
4382 continue;
4384 if (ipa_tm_scan_irr_block (bb))
4386 bitmap_set_bit (new_irr, bb->index);
4387 any_new_irr = true;
4389 else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4391 FOR_EACH_EDGE (e, ei, bb->succs)
4392 if (!bitmap_bit_p (visited_blocks, e->dest->index))
4394 bitmap_set_bit (visited_blocks, e->dest->index);
4395 pqueue->safe_push (e->dest);
4399 while (!pqueue->is_empty ());
4401 BITMAP_FREE (visited_blocks);
4403 return any_new_irr;
4406 /* Propagate the irrevocable property both up and down the dominator tree.
4407 BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4408 TM regions; OLD_IRR are the results of a previous scan of the dominator
4409 tree which has been fully propagated; NEW_IRR is the set of new blocks
4410 which are gaining the irrevocable property during the current scan. */
4412 static void
4413 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4414 bitmap old_irr, bitmap exit_blocks)
4416 vec<basic_block> bbs;
4417 bitmap all_region_blocks;
4419 /* If this block is in the old set, no need to rescan. */
4420 if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4421 return;
4423 all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4424 bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4425 all_region_blocks, false);
4428 basic_block bb = bbs.pop ();
4429 bool this_irr = bitmap_bit_p (new_irr, bb->index);
4430 bool all_son_irr = false;
4431 edge_iterator ei;
4432 edge e;
4434 /* Propagate up. If my children are, I am too, but we must have
4435 at least one child that is. */
4436 if (!this_irr)
4438 FOR_EACH_EDGE (e, ei, bb->succs)
4440 if (!bitmap_bit_p (new_irr, e->dest->index))
4442 all_son_irr = false;
4443 break;
4445 else
4446 all_son_irr = true;
4448 if (all_son_irr)
4450 /* Add block to new_irr if it hasn't already been processed. */
4451 if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4453 bitmap_set_bit (new_irr, bb->index);
4454 this_irr = true;
4459 /* Propagate down to everyone we immediately dominate. */
4460 if (this_irr)
4462 basic_block son;
4463 for (son = first_dom_son (CDI_DOMINATORS, bb);
4464 son;
4465 son = next_dom_son (CDI_DOMINATORS, son))
4467 /* Make sure block is actually in a TM region, and it
4468 isn't already in old_irr. */
4469 if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4470 && bitmap_bit_p (all_region_blocks, son->index))
4471 bitmap_set_bit (new_irr, son->index);
4475 while (!bbs.is_empty ());
4477 BITMAP_FREE (all_region_blocks);
4478 bbs.release ();
4481 static void
4482 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4484 gimple_stmt_iterator gsi;
4486 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4488 gimple stmt = gsi_stmt (gsi);
4489 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4491 tree fndecl = gimple_call_fndecl (stmt);
4492 if (fndecl)
4494 struct tm_ipa_cg_data *d;
4495 unsigned *pcallers;
4496 struct cgraph_node *tnode;
4498 if (is_tm_ending_fndecl (fndecl))
4499 continue;
4500 if (find_tm_replacement_function (fndecl))
4501 continue;
4503 tnode = cgraph_get_node (fndecl);
4504 d = get_cg_data (&tnode, true);
4506 pcallers = (for_clone ? &d->tm_callers_clone
4507 : &d->tm_callers_normal);
4509 gcc_assert (*pcallers > 0);
4510 *pcallers -= 1;
4516 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4517 as well as other irrevocable actions such as inline assembly. Mark all
4518 such blocks as irrevocable and decrement the number of calls to
4519 transactional clones. Return true if, for the transactional clone, the
4520 entire function is irrevocable. */
4522 static bool
4523 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4525 struct tm_ipa_cg_data *d;
4526 bitmap new_irr, old_irr;
4527 bool ret = false;
4529 /* Builtin operators (operator new, and such). */
4530 if (DECL_STRUCT_FUNCTION (node->decl) == NULL
4531 || DECL_STRUCT_FUNCTION (node->decl)->cfg == NULL)
4532 return false;
4534 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4535 calculate_dominance_info (CDI_DOMINATORS);
4537 d = get_cg_data (&node, true);
4538 auto_vec<basic_block, 10> queue;
4539 new_irr = BITMAP_ALLOC (&tm_obstack);
4541 /* Scan each tm region, propagating irrevocable status through the tree. */
4542 if (for_clone)
4544 old_irr = d->irrevocable_blocks_clone;
4545 queue.quick_push (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
4546 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4548 ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
4549 new_irr,
4550 old_irr, NULL);
4551 ret = bitmap_bit_p (new_irr,
4552 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun))->index);
4555 else
4557 struct tm_region *region;
4559 old_irr = d->irrevocable_blocks_normal;
4560 for (region = d->all_tm_regions; region; region = region->next)
4562 queue.quick_push (region->entry_block);
4563 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4564 region->exit_blocks))
4565 ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4566 region->exit_blocks);
4570 /* If we found any new irrevocable blocks, reduce the call count for
4571 transactional clones within the irrevocable blocks. Save the new
4572 set of irrevocable blocks for next time. */
4573 if (!bitmap_empty_p (new_irr))
4575 bitmap_iterator bmi;
4576 unsigned i;
4578 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4579 ipa_tm_decrement_clone_counts (BASIC_BLOCK_FOR_FN (cfun, i),
4580 for_clone);
4582 if (old_irr)
4584 bitmap_ior_into (old_irr, new_irr);
4585 BITMAP_FREE (new_irr);
4587 else if (for_clone)
4588 d->irrevocable_blocks_clone = new_irr;
4589 else
4590 d->irrevocable_blocks_normal = new_irr;
4592 if (dump_file && new_irr)
4594 const char *dname;
4595 bitmap_iterator bmi;
4596 unsigned i;
4598 dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4599 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4600 fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4603 else
4604 BITMAP_FREE (new_irr);
4606 pop_cfun ();
4608 return ret;
4611 /* Return true if, for the transactional clone of NODE, any call
4612 may enter irrevocable mode. */
4614 static bool
4615 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4617 struct tm_ipa_cg_data *d;
4618 tree decl;
4619 unsigned flags;
4621 d = get_cg_data (&node, true);
4622 decl = node->decl;
4623 flags = flags_from_decl_or_type (decl);
4625 /* Handle some TM builtins. Ordinarily these aren't actually generated
4626 at this point, but handling these functions when written in by the
4627 user makes it easier to build unit tests. */
4628 if (flags & ECF_TM_BUILTIN)
4629 return false;
4631 /* Filter out all functions that are marked. */
4632 if (flags & ECF_TM_PURE)
4633 return false;
4634 if (is_tm_safe (decl))
4635 return false;
4636 if (is_tm_irrevocable (decl))
4637 return true;
4638 if (is_tm_callable (decl))
4639 return true;
4640 if (find_tm_replacement_function (decl))
4641 return true;
4643 /* If we aren't seeing the final version of the function we don't
4644 know what it will contain at runtime. */
4645 if (cgraph_function_body_availability (node) < AVAIL_AVAILABLE)
4646 return true;
4648 /* If the function must go irrevocable, then of course true. */
4649 if (d->is_irrevocable)
4650 return true;
4652 /* If there are any blocks marked irrevocable, then the function
4653 as a whole may enter irrevocable. */
4654 if (d->irrevocable_blocks_clone)
4655 return true;
4657 /* We may have previously marked this function as tm_may_enter_irr;
4658 see pass_diagnose_tm_blocks. */
4659 if (node->local.tm_may_enter_irr)
4660 return true;
4662 /* Recurse on the main body for aliases. In general, this will
4663 result in one of the bits above being set so that we will not
4664 have to recurse next time. */
4665 if (node->alias)
4666 return ipa_tm_mayenterirr_function (cgraph_get_node (node->thunk.alias));
4668 /* What remains is unmarked local functions without items that force
4669 the function to go irrevocable. */
4670 return false;
4673 /* Diagnose calls from transaction_safe functions to unmarked
4674 functions that are determined to not be safe. */
4676 static void
4677 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4679 struct cgraph_edge *e;
4681 for (e = node->callees; e ; e = e->next_callee)
4682 if (!is_tm_callable (e->callee->decl)
4683 && e->callee->local.tm_may_enter_irr)
4684 error_at (gimple_location (e->call_stmt),
4685 "unsafe function call %qD within "
4686 "%<transaction_safe%> function", e->callee->decl);
4689 /* Diagnose call from atomic transactions to unmarked functions
4690 that are determined to not be safe. */
4692 static void
4693 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4694 struct tm_region *all_tm_regions)
4696 struct tm_region *r;
4698 for (r = all_tm_regions; r ; r = r->next)
4699 if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4701 /* Atomic transactions can be nested inside relaxed. */
4702 if (r->inner)
4703 ipa_tm_diagnose_transaction (node, r->inner);
4705 else
4707 vec<basic_block> bbs;
4708 gimple_stmt_iterator gsi;
4709 basic_block bb;
4710 size_t i;
4712 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4713 r->irr_blocks, NULL, false);
4715 for (i = 0; bbs.iterate (i, &bb); ++i)
4716 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4718 gimple stmt = gsi_stmt (gsi);
4719 tree fndecl;
4721 if (gimple_code (stmt) == GIMPLE_ASM)
4723 error_at (gimple_location (stmt),
4724 "asm not allowed in atomic transaction");
4725 continue;
4728 if (!is_gimple_call (stmt))
4729 continue;
4730 fndecl = gimple_call_fndecl (stmt);
4732 /* Indirect function calls have been diagnosed already. */
4733 if (!fndecl)
4734 continue;
4736 /* Stop at the end of the transaction. */
4737 if (is_tm_ending_fndecl (fndecl))
4739 if (bitmap_bit_p (r->exit_blocks, bb->index))
4740 break;
4741 continue;
4744 /* Marked functions have been diagnosed already. */
4745 if (is_tm_pure_call (stmt))
4746 continue;
4747 if (is_tm_callable (fndecl))
4748 continue;
4750 if (cgraph_local_info (fndecl)->tm_may_enter_irr)
4751 error_at (gimple_location (stmt),
4752 "unsafe function call %qD within "
4753 "atomic transaction", fndecl);
4756 bbs.release ();
4760 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4761 OLD_DECL. The returned value is a freshly malloced pointer that
4762 should be freed by the caller. */
4764 static tree
4765 tm_mangle (tree old_asm_id)
4767 const char *old_asm_name;
4768 char *tm_name;
4769 void *alloc = NULL;
4770 struct demangle_component *dc;
4771 tree new_asm_id;
4773 /* Determine if the symbol is already a valid C++ mangled name. Do this
4774 even for C, which might be interfacing with C++ code via appropriately
4775 ugly identifiers. */
4776 /* ??? We could probably do just as well checking for "_Z" and be done. */
4777 old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4778 dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4780 if (dc == NULL)
4782 char length[8];
4784 do_unencoded:
4785 sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4786 tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4788 else
4790 old_asm_name += 2; /* Skip _Z */
4792 switch (dc->type)
4794 case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4795 case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4796 /* Don't play silly games, you! */
4797 goto do_unencoded;
4799 case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4800 /* I'd really like to know if we can ever be passed one of
4801 these from the C++ front end. The Logical Thing would
4802 seem that hidden-alias should be outer-most, so that we
4803 get hidden-alias of a transaction-clone and not vice-versa. */
4804 old_asm_name += 2;
4805 break;
4807 default:
4808 break;
4811 tm_name = concat ("_ZGTt", old_asm_name, NULL);
4813 free (alloc);
4815 new_asm_id = get_identifier (tm_name);
4816 free (tm_name);
4818 return new_asm_id;
4821 static inline void
4822 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4824 cgraph_mark_force_output_node (node);
4825 node->analyzed = true;
4828 static inline void
4829 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4831 node->forced_by_abi = true;
4832 node->analyzed = true;
4835 /* Callback data for ipa_tm_create_version_alias. */
4836 struct create_version_alias_info
4838 struct cgraph_node *old_node;
4839 tree new_decl;
4842 /* A subroutine of ipa_tm_create_version, called via
4843 cgraph_for_node_and_aliases. Create new tm clones for each of
4844 the existing aliases. */
4845 static bool
4846 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4848 struct create_version_alias_info *info
4849 = (struct create_version_alias_info *)data;
4850 tree old_decl, new_decl, tm_name;
4851 struct cgraph_node *new_node;
4853 if (!node->cpp_implicit_alias)
4854 return false;
4856 old_decl = node->decl;
4857 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4858 new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4859 TREE_CODE (old_decl), tm_name,
4860 TREE_TYPE (old_decl));
4862 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4863 SET_DECL_RTL (new_decl, NULL);
4865 /* Based loosely on C++'s make_alias_for(). */
4866 TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4867 DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4868 DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4869 TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4870 DECL_EXTERNAL (new_decl) = 0;
4871 DECL_ARTIFICIAL (new_decl) = 1;
4872 TREE_ADDRESSABLE (new_decl) = 1;
4873 TREE_USED (new_decl) = 1;
4874 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4876 /* Perform the same remapping to the comdat group. */
4877 if (DECL_ONE_ONLY (new_decl))
4878 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4880 new_node = cgraph_same_body_alias (NULL, new_decl, info->new_decl);
4881 new_node->tm_clone = true;
4882 new_node->externally_visible = info->old_node->externally_visible;
4883 /* ?? Do not traverse aliases here. */
4884 get_cg_data (&node, false)->clone = new_node;
4886 record_tm_clone_pair (old_decl, new_decl);
4888 if (info->old_node->force_output
4889 || ipa_ref_list_first_referring (&info->old_node->ref_list))
4890 ipa_tm_mark_force_output_node (new_node);
4891 if (info->old_node->forced_by_abi)
4892 ipa_tm_mark_forced_by_abi_node (new_node);
4893 return false;
4896 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4897 appropriate for the transactional clone. */
4899 static void
4900 ipa_tm_create_version (struct cgraph_node *old_node)
4902 tree new_decl, old_decl, tm_name;
4903 struct cgraph_node *new_node;
4905 old_decl = old_node->decl;
4906 new_decl = copy_node (old_decl);
4908 /* DECL_ASSEMBLER_NAME needs to be set before we call
4909 cgraph_copy_node_for_versioning below, because cgraph_node will
4910 fill the assembler_name_hash. */
4911 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4912 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4913 SET_DECL_RTL (new_decl, NULL);
4914 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4916 /* Perform the same remapping to the comdat group. */
4917 if (DECL_ONE_ONLY (new_decl))
4918 DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4920 new_node = cgraph_copy_node_for_versioning (old_node, new_decl, vNULL, NULL);
4921 new_node->local.local = false;
4922 new_node->externally_visible = old_node->externally_visible;
4923 new_node->lowered = true;
4924 new_node->tm_clone = 1;
4925 get_cg_data (&old_node, true)->clone = new_node;
4927 if (cgraph_function_body_availability (old_node) >= AVAIL_OVERWRITABLE)
4929 /* Remap extern inline to static inline. */
4930 /* ??? Is it worth trying to use make_decl_one_only? */
4931 if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4933 DECL_EXTERNAL (new_decl) = 0;
4934 TREE_PUBLIC (new_decl) = 0;
4935 DECL_WEAK (new_decl) = 0;
4938 tree_function_versioning (old_decl, new_decl,
4939 NULL, false, NULL,
4940 false, NULL, NULL);
4943 record_tm_clone_pair (old_decl, new_decl);
4945 cgraph_call_function_insertion_hooks (new_node);
4946 if (old_node->force_output
4947 || ipa_ref_list_first_referring (&old_node->ref_list))
4948 ipa_tm_mark_force_output_node (new_node);
4949 if (old_node->forced_by_abi)
4950 ipa_tm_mark_forced_by_abi_node (new_node);
4952 /* Do the same thing, but for any aliases of the original node. */
4954 struct create_version_alias_info data;
4955 data.old_node = old_node;
4956 data.new_decl = new_decl;
4957 cgraph_for_node_and_aliases (old_node, ipa_tm_create_version_alias,
4958 &data, true);
4962 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB. */
4964 static void
4965 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4966 basic_block bb)
4968 gimple_stmt_iterator gsi;
4969 gimple g;
4971 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4973 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4974 1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4976 split_block_after_labels (bb);
4977 gsi = gsi_after_labels (bb);
4978 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4980 cgraph_create_edge (node,
4981 cgraph_get_create_node
4982 (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4983 g, 0,
4984 compute_call_stmt_bb_frequency (node->decl,
4985 gimple_bb (g)));
4988 /* Construct a call to TM_GETTMCLONE and insert it before GSI. */
4990 static bool
4991 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4992 struct tm_region *region,
4993 gimple_stmt_iterator *gsi, gimple stmt)
4995 tree gettm_fn, ret, old_fn, callfn;
4996 gimple g, g2;
4997 bool safe;
4999 old_fn = gimple_call_fn (stmt);
5001 if (TREE_CODE (old_fn) == ADDR_EXPR)
5003 tree fndecl = TREE_OPERAND (old_fn, 0);
5004 tree clone = get_tm_clone_pair (fndecl);
5006 /* By transforming the call into a TM_GETTMCLONE, we are
5007 technically taking the address of the original function and
5008 its clone. Explain this so inlining will know this function
5009 is needed. */
5010 cgraph_mark_address_taken_node (cgraph_get_node (fndecl));
5011 if (clone)
5012 cgraph_mark_address_taken_node (cgraph_get_node (clone));
5015 safe = is_tm_safe (TREE_TYPE (old_fn));
5016 gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
5017 : BUILT_IN_TM_GETTMCLONE_IRR);
5018 ret = create_tmp_var (ptr_type_node, NULL);
5020 if (!safe)
5021 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
5023 /* Discard OBJ_TYPE_REF, since we weren't able to fold it. */
5024 if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
5025 old_fn = OBJ_TYPE_REF_EXPR (old_fn);
5027 g = gimple_build_call (gettm_fn, 1, old_fn);
5028 ret = make_ssa_name (ret, g);
5029 gimple_call_set_lhs (g, ret);
5031 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5033 cgraph_create_edge (node, cgraph_get_create_node (gettm_fn), g, 0,
5034 compute_call_stmt_bb_frequency (node->decl,
5035 gimple_bb (g)));
5037 /* Cast return value from tm_gettmclone* into appropriate function
5038 pointer. */
5039 callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
5040 g2 = gimple_build_assign (callfn,
5041 fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5042 callfn = make_ssa_name (callfn, g2);
5043 gimple_assign_set_lhs (g2, callfn);
5044 gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5046 /* ??? This is a hack to preserve the NOTHROW bit on the call,
5047 which we would have derived from the decl. Failure to save
5048 this bit means we might have to split the basic block. */
5049 if (gimple_call_nothrow_p (stmt))
5050 gimple_call_set_nothrow (stmt, true);
5052 gimple_call_set_fn (stmt, callfn);
5054 /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5055 for a call statement. Fix it. */
5057 tree lhs = gimple_call_lhs (stmt);
5058 tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5059 if (lhs
5060 && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5062 tree temp;
5064 temp = create_tmp_reg (rettype, 0);
5065 gimple_call_set_lhs (stmt, temp);
5067 g2 = gimple_build_assign (lhs,
5068 fold_build1 (VIEW_CONVERT_EXPR,
5069 TREE_TYPE (lhs), temp));
5070 gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5074 update_stmt (stmt);
5076 return true;
5079 /* Helper function for ipa_tm_transform_calls*. Given a call
5080 statement in GSI which resides inside transaction REGION, redirect
5081 the call to either its wrapper function, or its clone. */
5083 static void
5084 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5085 struct tm_region *region,
5086 gimple_stmt_iterator *gsi,
5087 bool *need_ssa_rename_p)
5089 gimple stmt = gsi_stmt (*gsi);
5090 struct cgraph_node *new_node;
5091 struct cgraph_edge *e = cgraph_edge (node, stmt);
5092 tree fndecl = gimple_call_fndecl (stmt);
5094 /* For indirect calls, pass the address through the runtime. */
5095 if (fndecl == NULL)
5097 *need_ssa_rename_p |=
5098 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5099 return;
5102 /* Handle some TM builtins. Ordinarily these aren't actually generated
5103 at this point, but handling these functions when written in by the
5104 user makes it easier to build unit tests. */
5105 if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5106 return;
5108 /* Fixup recursive calls inside clones. */
5109 /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5110 for recursion but not update the call statements themselves? */
5111 if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5113 gimple_call_set_fndecl (stmt, current_function_decl);
5114 return;
5117 /* If there is a replacement, use it. */
5118 fndecl = find_tm_replacement_function (fndecl);
5119 if (fndecl)
5121 new_node = cgraph_get_create_node (fndecl);
5123 /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5125 We can't do this earlier in record_tm_replacement because
5126 cgraph_remove_unreachable_nodes is called before we inject
5127 references to the node. Further, we can't do this in some
5128 nice central place in ipa_tm_execute because we don't have
5129 the exact list of wrapper functions that would be used.
5130 Marking more wrappers than necessary results in the creation
5131 of unnecessary cgraph_nodes, which can cause some of the
5132 other IPA passes to crash.
5134 We do need to mark these nodes so that we get the proper
5135 result in expand_call_tm. */
5136 /* ??? This seems broken. How is it that we're marking the
5137 CALLEE as may_enter_irr? Surely we should be marking the
5138 CALLER. Also note that find_tm_replacement_function also
5139 contains mappings into the TM runtime, e.g. memcpy. These
5140 we know won't go irrevocable. */
5141 new_node->local.tm_may_enter_irr = 1;
5143 else
5145 struct tm_ipa_cg_data *d;
5146 struct cgraph_node *tnode = e->callee;
5148 d = get_cg_data (&tnode, true);
5149 new_node = d->clone;
5151 /* As we've already skipped pure calls and appropriate builtins,
5152 and we've already marked irrevocable blocks, if we can't come
5153 up with a static replacement, then ask the runtime. */
5154 if (new_node == NULL)
5156 *need_ssa_rename_p |=
5157 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5158 return;
5161 fndecl = new_node->decl;
5164 cgraph_redirect_edge_callee (e, new_node);
5165 gimple_call_set_fndecl (stmt, fndecl);
5168 /* Helper function for ipa_tm_transform_calls. For a given BB,
5169 install calls to tm_irrevocable when IRR_BLOCKS are reached,
5170 redirect other calls to the generated transactional clone. */
5172 static bool
5173 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5174 basic_block bb, bitmap irr_blocks)
5176 gimple_stmt_iterator gsi;
5177 bool need_ssa_rename = false;
5179 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5181 ipa_tm_insert_irr_call (node, region, bb);
5182 return true;
5185 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5187 gimple stmt = gsi_stmt (gsi);
5189 if (!is_gimple_call (stmt))
5190 continue;
5191 if (is_tm_pure_call (stmt))
5192 continue;
5194 /* Redirect edges to the appropriate replacement or clone. */
5195 ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5198 return need_ssa_rename;
5201 /* Walk the CFG for REGION, beginning at BB. Install calls to
5202 tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5203 the generated transactional clone. */
5205 static bool
5206 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5207 basic_block bb, bitmap irr_blocks)
5209 bool need_ssa_rename = false;
5210 edge e;
5211 edge_iterator ei;
5212 auto_vec<basic_block> queue;
5213 bitmap visited_blocks = BITMAP_ALLOC (NULL);
5215 queue.safe_push (bb);
5218 bb = queue.pop ();
5220 need_ssa_rename |=
5221 ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5223 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5224 continue;
5226 if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5227 continue;
5229 FOR_EACH_EDGE (e, ei, bb->succs)
5230 if (!bitmap_bit_p (visited_blocks, e->dest->index))
5232 bitmap_set_bit (visited_blocks, e->dest->index);
5233 queue.safe_push (e->dest);
5236 while (!queue.is_empty ());
5238 BITMAP_FREE (visited_blocks);
5240 return need_ssa_rename;
5243 /* Transform the calls within the TM regions within NODE. */
5245 static void
5246 ipa_tm_transform_transaction (struct cgraph_node *node)
5248 struct tm_ipa_cg_data *d;
5249 struct tm_region *region;
5250 bool need_ssa_rename = false;
5252 d = get_cg_data (&node, true);
5254 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5255 calculate_dominance_info (CDI_DOMINATORS);
5257 for (region = d->all_tm_regions; region; region = region->next)
5259 /* If we're sure to go irrevocable, don't transform anything. */
5260 if (d->irrevocable_blocks_normal
5261 && bitmap_bit_p (d->irrevocable_blocks_normal,
5262 region->entry_block->index))
5264 transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5265 | GTMA_MAY_ENTER_IRREVOCABLE
5266 | GTMA_HAS_NO_INSTRUMENTATION);
5267 continue;
5270 need_ssa_rename |=
5271 ipa_tm_transform_calls (node, region, region->entry_block,
5272 d->irrevocable_blocks_normal);
5275 if (need_ssa_rename)
5276 update_ssa (TODO_update_ssa_only_virtuals);
5278 pop_cfun ();
5281 /* Transform the calls within the transactional clone of NODE. */
5283 static void
5284 ipa_tm_transform_clone (struct cgraph_node *node)
5286 struct tm_ipa_cg_data *d;
5287 bool need_ssa_rename;
5289 d = get_cg_data (&node, true);
5291 /* If this function makes no calls and has no irrevocable blocks,
5292 then there's nothing to do. */
5293 /* ??? Remove non-aborting top-level transactions. */
5294 if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5295 return;
5297 push_cfun (DECL_STRUCT_FUNCTION (d->clone->decl));
5298 calculate_dominance_info (CDI_DOMINATORS);
5300 need_ssa_rename =
5301 ipa_tm_transform_calls (d->clone, NULL,
5302 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
5303 d->irrevocable_blocks_clone);
5305 if (need_ssa_rename)
5306 update_ssa (TODO_update_ssa_only_virtuals);
5308 pop_cfun ();
5311 /* Main entry point for the transactional memory IPA pass. */
5313 static unsigned int
5314 ipa_tm_execute (void)
5316 cgraph_node_queue tm_callees = cgraph_node_queue ();
5317 /* List of functions that will go irrevocable. */
5318 cgraph_node_queue irr_worklist = cgraph_node_queue ();
5320 struct cgraph_node *node;
5321 struct tm_ipa_cg_data *d;
5322 enum availability a;
5323 unsigned int i;
5325 #ifdef ENABLE_CHECKING
5326 verify_cgraph ();
5327 #endif
5329 bitmap_obstack_initialize (&tm_obstack);
5330 initialize_original_copy_tables ();
5332 /* For all local functions marked tm_callable, queue them. */
5333 FOR_EACH_DEFINED_FUNCTION (node)
5334 if (is_tm_callable (node->decl)
5335 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5337 d = get_cg_data (&node, true);
5338 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5341 /* For all local reachable functions... */
5342 FOR_EACH_DEFINED_FUNCTION (node)
5343 if (node->lowered
5344 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5346 /* ... marked tm_pure, record that fact for the runtime by
5347 indicating that the pure function is its own tm_callable.
5348 No need to do this if the function's address can't be taken. */
5349 if (is_tm_pure (node->decl))
5351 if (!node->local.local)
5352 record_tm_clone_pair (node->decl, node->decl);
5353 continue;
5356 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5357 calculate_dominance_info (CDI_DOMINATORS);
5359 tm_region_init (NULL);
5360 if (all_tm_regions)
5362 d = get_cg_data (&node, true);
5364 /* Scan for calls that are in each transaction, and
5365 generate the uninstrumented code path. */
5366 ipa_tm_scan_calls_transaction (d, &tm_callees);
5368 /* Put it in the worklist so we can scan the function
5369 later (ipa_tm_scan_irr_function) and mark the
5370 irrevocable blocks. */
5371 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5372 d->want_irr_scan_normal = true;
5375 pop_cfun ();
5378 /* For every local function on the callee list, scan as if we will be
5379 creating a transactional clone, queueing all new functions we find
5380 along the way. */
5381 for (i = 0; i < tm_callees.length (); ++i)
5383 node = tm_callees[i];
5384 a = cgraph_function_body_availability (node);
5385 d = get_cg_data (&node, true);
5387 /* Put it in the worklist so we can scan the function later
5388 (ipa_tm_scan_irr_function) and mark the irrevocable
5389 blocks. */
5390 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5392 /* Some callees cannot be arbitrarily cloned. These will always be
5393 irrevocable. Mark these now, so that we need not scan them. */
5394 if (is_tm_irrevocable (node->decl))
5395 ipa_tm_note_irrevocable (node, &irr_worklist);
5396 else if (a <= AVAIL_NOT_AVAILABLE
5397 && !is_tm_safe_or_pure (node->decl))
5398 ipa_tm_note_irrevocable (node, &irr_worklist);
5399 else if (a >= AVAIL_OVERWRITABLE)
5401 if (!tree_versionable_function_p (node->decl))
5402 ipa_tm_note_irrevocable (node, &irr_worklist);
5403 else if (!d->is_irrevocable)
5405 /* If this is an alias, make sure its base is queued as well.
5406 we need not scan the callees now, as the base will do. */
5407 if (node->alias)
5409 node = cgraph_get_node (node->thunk.alias);
5410 d = get_cg_data (&node, true);
5411 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5412 continue;
5415 /* Add all nodes called by this function into
5416 tm_callees as well. */
5417 ipa_tm_scan_calls_clone (node, &tm_callees);
5422 /* Iterate scans until no more work to be done. Prefer not to use
5423 vec::pop because the worklist tends to follow a breadth-first
5424 search of the callgraph, which should allow convergance with a
5425 minimum number of scans. But we also don't want the worklist
5426 array to grow without bound, so we shift the array up periodically. */
5427 for (i = 0; i < irr_worklist.length (); ++i)
5429 if (i > 256 && i == irr_worklist.length () / 8)
5431 irr_worklist.block_remove (0, i);
5432 i = 0;
5435 node = irr_worklist[i];
5436 d = get_cg_data (&node, true);
5437 d->in_worklist = false;
5439 if (d->want_irr_scan_normal)
5441 d->want_irr_scan_normal = false;
5442 ipa_tm_scan_irr_function (node, false);
5444 if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5445 ipa_tm_note_irrevocable (node, &irr_worklist);
5448 /* For every function on the callee list, collect the tm_may_enter_irr
5449 bit on the node. */
5450 irr_worklist.truncate (0);
5451 for (i = 0; i < tm_callees.length (); ++i)
5453 node = tm_callees[i];
5454 if (ipa_tm_mayenterirr_function (node))
5456 d = get_cg_data (&node, true);
5457 gcc_assert (d->in_worklist == false);
5458 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5462 /* Propagate the tm_may_enter_irr bit to callers until stable. */
5463 for (i = 0; i < irr_worklist.length (); ++i)
5465 struct cgraph_node *caller;
5466 struct cgraph_edge *e;
5467 struct ipa_ref *ref;
5468 unsigned j;
5470 if (i > 256 && i == irr_worklist.length () / 8)
5472 irr_worklist.block_remove (0, i);
5473 i = 0;
5476 node = irr_worklist[i];
5477 d = get_cg_data (&node, true);
5478 d->in_worklist = false;
5479 node->local.tm_may_enter_irr = true;
5481 /* Propagate back to normal callers. */
5482 for (e = node->callers; e ; e = e->next_caller)
5484 caller = e->caller;
5485 if (!is_tm_safe_or_pure (caller->decl)
5486 && !caller->local.tm_may_enter_irr)
5488 d = get_cg_data (&caller, true);
5489 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5493 /* Propagate back to referring aliases as well. */
5494 for (j = 0; ipa_ref_list_referring_iterate (&node->ref_list, j, ref); j++)
5496 caller = cgraph (ref->referring);
5497 if (ref->use == IPA_REF_ALIAS
5498 && !caller->local.tm_may_enter_irr)
5500 /* ?? Do not traverse aliases here. */
5501 d = get_cg_data (&caller, false);
5502 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5507 /* Now validate all tm_safe functions, and all atomic regions in
5508 other functions. */
5509 FOR_EACH_DEFINED_FUNCTION (node)
5510 if (node->lowered
5511 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5513 d = get_cg_data (&node, true);
5514 if (is_tm_safe (node->decl))
5515 ipa_tm_diagnose_tm_safe (node);
5516 else if (d->all_tm_regions)
5517 ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5520 /* Create clones. Do those that are not irrevocable and have a
5521 positive call count. Do those publicly visible functions that
5522 the user directed us to clone. */
5523 for (i = 0; i < tm_callees.length (); ++i)
5525 bool doit = false;
5527 node = tm_callees[i];
5528 if (node->cpp_implicit_alias)
5529 continue;
5531 a = cgraph_function_body_availability (node);
5532 d = get_cg_data (&node, true);
5534 if (a <= AVAIL_NOT_AVAILABLE)
5535 doit = is_tm_callable (node->decl);
5536 else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
5537 doit = true;
5538 else if (!d->is_irrevocable
5539 && d->tm_callers_normal + d->tm_callers_clone > 0)
5540 doit = true;
5542 if (doit)
5543 ipa_tm_create_version (node);
5546 /* Redirect calls to the new clones, and insert irrevocable marks. */
5547 for (i = 0; i < tm_callees.length (); ++i)
5549 node = tm_callees[i];
5550 if (node->analyzed)
5552 d = get_cg_data (&node, true);
5553 if (d->clone)
5554 ipa_tm_transform_clone (node);
5557 FOR_EACH_DEFINED_FUNCTION (node)
5558 if (node->lowered
5559 && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
5561 d = get_cg_data (&node, true);
5562 if (d->all_tm_regions)
5563 ipa_tm_transform_transaction (node);
5566 /* Free and clear all data structures. */
5567 tm_callees.release ();
5568 irr_worklist.release ();
5569 bitmap_obstack_release (&tm_obstack);
5570 free_original_copy_tables ();
5572 FOR_EACH_FUNCTION (node)
5573 node->aux = NULL;
5575 #ifdef ENABLE_CHECKING
5576 verify_cgraph ();
5577 #endif
5579 return 0;
5582 namespace {
5584 const pass_data pass_data_ipa_tm =
5586 SIMPLE_IPA_PASS, /* type */
5587 "tmipa", /* name */
5588 OPTGROUP_NONE, /* optinfo_flags */
5589 true, /* has_gate */
5590 true, /* has_execute */
5591 TV_TRANS_MEM, /* tv_id */
5592 ( PROP_ssa | PROP_cfg ), /* properties_required */
5593 0, /* properties_provided */
5594 0, /* properties_destroyed */
5595 0, /* todo_flags_start */
5596 0, /* todo_flags_finish */
5599 class pass_ipa_tm : public simple_ipa_opt_pass
5601 public:
5602 pass_ipa_tm (gcc::context *ctxt)
5603 : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5606 /* opt_pass methods: */
5607 bool gate () { return gate_tm (); }
5608 unsigned int execute () { return ipa_tm_execute (); }
5610 }; // class pass_ipa_tm
5612 } // anon namespace
5614 simple_ipa_opt_pass *
5615 make_pass_ipa_tm (gcc::context *ctxt)
5617 return new pass_ipa_tm (ctxt);
5620 #include "gt-trans-mem.h"