Add Knights Landing support to __builtin_cpu_is
[official-gcc.git] / gcc / trans-mem.c
blobbf7241aa9f9964d2b57615f4f4050102687bea21
1 /* Passes for transactional memory support.
2 Copyright (C) 2008-2015 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 "alias.h"
24 #include "backend.h"
25 #include "cfghooks.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "rtl.h"
29 #include "ssa.h"
30 #include "options.h"
31 #include "fold-const.h"
32 #include "internal-fn.h"
33 #include "tree-eh.h"
34 #include "calls.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 "cgraph.h"
41 #include "tree-cfg.h"
42 #include "tree-into-ssa.h"
43 #include "tree-pass.h"
44 #include "tree-inline.h"
45 #include "diagnostic-core.h"
46 #include "demangle.h"
47 #include "output.h"
48 #include "trans-mem.h"
49 #include "params.h"
50 #include "target.h"
51 #include "langhooks.h"
52 #include "gimple-pretty-print.h"
53 #include "cfgloop.h"
54 #include "tree-ssa-address.h"
57 #define A_RUNINSTRUMENTEDCODE 0x0001
58 #define A_RUNUNINSTRUMENTEDCODE 0x0002
59 #define A_SAVELIVEVARIABLES 0x0004
60 #define A_RESTORELIVEVARIABLES 0x0008
61 #define A_ABORTTRANSACTION 0x0010
63 #define AR_USERABORT 0x0001
64 #define AR_USERRETRY 0x0002
65 #define AR_TMCONFLICT 0x0004
66 #define AR_EXCEPTIONBLOCKABORT 0x0008
67 #define AR_OUTERABORT 0x0010
69 #define MODE_SERIALIRREVOCABLE 0x0000
72 /* The representation of a transaction changes several times during the
73 lowering process. In the beginning, in the front-end we have the
74 GENERIC tree TRANSACTION_EXPR. For example,
76 __transaction {
77 local++;
78 if (++global == 10)
79 __tm_abort;
82 During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
83 trivially replaced with a GIMPLE_TRANSACTION node.
85 During pass_lower_tm, we examine the body of transactions looking
86 for aborts. Transactions that do not contain an abort may be
87 merged into an outer transaction. We also add a TRY-FINALLY node
88 to arrange for the transaction to be committed on any exit.
90 [??? Think about how this arrangement affects throw-with-commit
91 and throw-with-abort operations. In this case we want the TRY to
92 handle gotos, but not to catch any exceptions because the transaction
93 will already be closed.]
95 GIMPLE_TRANSACTION [label=NULL] {
96 try {
97 local = local + 1;
98 t0 = global;
99 t1 = t0 + 1;
100 global = t1;
101 if (t1 == 10)
102 __builtin___tm_abort ();
103 } finally {
104 __builtin___tm_commit ();
108 During pass_lower_eh, we create EH regions for the transactions,
109 intermixed with the regular EH stuff. This gives us a nice persistent
110 mapping (all the way through rtl) from transactional memory operation
111 back to the transaction, which allows us to get the abnormal edges
112 correct to model transaction aborts and restarts:
114 GIMPLE_TRANSACTION [label=over]
115 local = local + 1;
116 t0 = global;
117 t1 = t0 + 1;
118 global = t1;
119 if (t1 == 10)
120 __builtin___tm_abort ();
121 __builtin___tm_commit ();
122 over:
124 This is the end of all_lowering_passes, and so is what is present
125 during the IPA passes, and through all of the optimization passes.
127 During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
128 functions and mark functions for cloning.
130 At the end of gimple optimization, before exiting SSA form,
131 pass_tm_edges replaces statements that perform transactional
132 memory operations with the appropriate TM builtins, and swap
133 out function calls with their transactional clones. At this
134 point we introduce the abnormal transaction restart edges and
135 complete lowering of the GIMPLE_TRANSACTION node.
137 x = __builtin___tm_start (MAY_ABORT);
138 eh_label:
139 if (x & abort_transaction)
140 goto over;
141 local = local + 1;
142 t0 = __builtin___tm_load (global);
143 t1 = t0 + 1;
144 __builtin___tm_store (&global, t1);
145 if (t1 == 10)
146 __builtin___tm_abort ();
147 __builtin___tm_commit ();
148 over:
151 static void *expand_regions (struct tm_region *,
152 void *(*callback)(struct tm_region *, void *),
153 void *, bool);
156 /* Return the attributes we want to examine for X, or NULL if it's not
157 something we examine. We look at function types, but allow pointers
158 to function types and function decls and peek through. */
160 static tree
161 get_attrs_for (const_tree x)
163 if (x == NULL_TREE)
164 return NULL_TREE;
166 switch (TREE_CODE (x))
168 case FUNCTION_DECL:
169 return TYPE_ATTRIBUTES (TREE_TYPE (x));
170 break;
172 default:
173 if (TYPE_P (x))
174 return NULL_TREE;
175 x = TREE_TYPE (x);
176 if (TREE_CODE (x) != POINTER_TYPE)
177 return NULL_TREE;
178 /* FALLTHRU */
180 case POINTER_TYPE:
181 x = TREE_TYPE (x);
182 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
183 return NULL_TREE;
184 /* FALLTHRU */
186 case FUNCTION_TYPE:
187 case METHOD_TYPE:
188 return TYPE_ATTRIBUTES (x);
192 /* Return true if X has been marked TM_PURE. */
194 bool
195 is_tm_pure (const_tree x)
197 unsigned flags;
199 switch (TREE_CODE (x))
201 case FUNCTION_DECL:
202 case FUNCTION_TYPE:
203 case METHOD_TYPE:
204 break;
206 default:
207 if (TYPE_P (x))
208 return false;
209 x = TREE_TYPE (x);
210 if (TREE_CODE (x) != POINTER_TYPE)
211 return false;
212 /* FALLTHRU */
214 case POINTER_TYPE:
215 x = TREE_TYPE (x);
216 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
217 return false;
218 break;
221 flags = flags_from_decl_or_type (x);
222 return (flags & ECF_TM_PURE) != 0;
225 /* Return true if X has been marked TM_IRREVOCABLE. */
227 static bool
228 is_tm_irrevocable (tree x)
230 tree attrs = get_attrs_for (x);
232 if (attrs && lookup_attribute ("transaction_unsafe", attrs))
233 return true;
235 /* A call to the irrevocable builtin is by definition,
236 irrevocable. */
237 if (TREE_CODE (x) == ADDR_EXPR)
238 x = TREE_OPERAND (x, 0);
239 if (TREE_CODE (x) == FUNCTION_DECL
240 && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
241 && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
242 return true;
244 return false;
247 /* Return true if X has been marked TM_SAFE. */
249 bool
250 is_tm_safe (const_tree x)
252 if (flag_tm)
254 tree attrs = get_attrs_for (x);
255 if (attrs)
257 if (lookup_attribute ("transaction_safe", attrs))
258 return true;
259 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
260 return true;
263 return false;
266 /* Return true if CALL is const, or tm_pure. */
268 static bool
269 is_tm_pure_call (gimple call)
271 tree fn = gimple_call_fn (call);
273 if (TREE_CODE (fn) == ADDR_EXPR)
275 fn = TREE_OPERAND (fn, 0);
276 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
278 else
279 fn = TREE_TYPE (fn);
281 return is_tm_pure (fn);
284 /* Return true if X has been marked TM_CALLABLE. */
286 static bool
287 is_tm_callable (tree x)
289 tree attrs = get_attrs_for (x);
290 if (attrs)
292 if (lookup_attribute ("transaction_callable", attrs))
293 return true;
294 if (lookup_attribute ("transaction_safe", attrs))
295 return true;
296 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
297 return true;
299 return false;
302 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER. */
304 bool
305 is_tm_may_cancel_outer (tree x)
307 tree attrs = get_attrs_for (x);
308 if (attrs)
309 return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
310 return false;
313 /* Return true for built in functions that "end" a transaction. */
315 bool
316 is_tm_ending_fndecl (tree fndecl)
318 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
319 switch (DECL_FUNCTION_CODE (fndecl))
321 case BUILT_IN_TM_COMMIT:
322 case BUILT_IN_TM_COMMIT_EH:
323 case BUILT_IN_TM_ABORT:
324 case BUILT_IN_TM_IRREVOCABLE:
325 return true;
326 default:
327 break;
330 return false;
333 /* Return true if STMT is a built in function call that "ends" a
334 transaction. */
336 bool
337 is_tm_ending (gimple stmt)
339 tree fndecl;
341 if (gimple_code (stmt) != GIMPLE_CALL)
342 return false;
344 fndecl = gimple_call_fndecl (stmt);
345 return (fndecl != NULL_TREE
346 && is_tm_ending_fndecl (fndecl));
349 /* Return true if STMT is a TM load. */
351 static bool
352 is_tm_load (gimple stmt)
354 tree fndecl;
356 if (gimple_code (stmt) != GIMPLE_CALL)
357 return false;
359 fndecl = gimple_call_fndecl (stmt);
360 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
361 && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
364 /* Same as above, but for simple TM loads, that is, not the
365 after-write, after-read, etc optimized variants. */
367 static bool
368 is_tm_simple_load (gimple stmt)
370 tree fndecl;
372 if (gimple_code (stmt) != GIMPLE_CALL)
373 return false;
375 fndecl = gimple_call_fndecl (stmt);
376 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
378 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
379 return (fcode == BUILT_IN_TM_LOAD_1
380 || fcode == BUILT_IN_TM_LOAD_2
381 || fcode == BUILT_IN_TM_LOAD_4
382 || fcode == BUILT_IN_TM_LOAD_8
383 || fcode == BUILT_IN_TM_LOAD_FLOAT
384 || fcode == BUILT_IN_TM_LOAD_DOUBLE
385 || fcode == BUILT_IN_TM_LOAD_LDOUBLE
386 || fcode == BUILT_IN_TM_LOAD_M64
387 || fcode == BUILT_IN_TM_LOAD_M128
388 || fcode == BUILT_IN_TM_LOAD_M256);
390 return false;
393 /* Return true if STMT is a TM store. */
395 static bool
396 is_tm_store (gimple stmt)
398 tree fndecl;
400 if (gimple_code (stmt) != GIMPLE_CALL)
401 return false;
403 fndecl = gimple_call_fndecl (stmt);
404 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
405 && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
408 /* Same as above, but for simple TM stores, that is, not the
409 after-write, after-read, etc optimized variants. */
411 static bool
412 is_tm_simple_store (gimple stmt)
414 tree fndecl;
416 if (gimple_code (stmt) != GIMPLE_CALL)
417 return false;
419 fndecl = gimple_call_fndecl (stmt);
420 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
422 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
423 return (fcode == BUILT_IN_TM_STORE_1
424 || fcode == BUILT_IN_TM_STORE_2
425 || fcode == BUILT_IN_TM_STORE_4
426 || fcode == BUILT_IN_TM_STORE_8
427 || fcode == BUILT_IN_TM_STORE_FLOAT
428 || fcode == BUILT_IN_TM_STORE_DOUBLE
429 || fcode == BUILT_IN_TM_STORE_LDOUBLE
430 || fcode == BUILT_IN_TM_STORE_M64
431 || fcode == BUILT_IN_TM_STORE_M128
432 || fcode == BUILT_IN_TM_STORE_M256);
434 return false;
437 /* Return true if FNDECL is BUILT_IN_TM_ABORT. */
439 static bool
440 is_tm_abort (tree fndecl)
442 return (fndecl
443 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
444 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
447 /* Build a GENERIC tree for a user abort. This is called by front ends
448 while transforming the __tm_abort statement. */
450 tree
451 build_tm_abort_call (location_t loc, bool is_outer)
453 return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
454 build_int_cst (integer_type_node,
455 AR_USERABORT
456 | (is_outer ? AR_OUTERABORT : 0)));
459 /* Map for aribtrary function replacement under TM, as created
460 by the tm_wrap attribute. */
462 struct tm_wrapper_hasher : ggc_cache_ptr_hash<tree_map>
464 static inline hashval_t hash (tree_map *m) { return m->hash; }
465 static inline bool
466 equal (tree_map *a, tree_map *b)
468 return a->base.from == b->base.from;
471 static int
472 keep_cache_entry (tree_map *&m)
474 return ggc_marked_p (m->base.from);
478 static GTY((cache)) hash_table<tm_wrapper_hasher> *tm_wrap_map;
480 void
481 record_tm_replacement (tree from, tree to)
483 struct tree_map **slot, *h;
485 /* Do not inline wrapper functions that will get replaced in the TM
486 pass.
488 Suppose you have foo() that will get replaced into tmfoo(). Make
489 sure the inliner doesn't try to outsmart us and inline foo()
490 before we get a chance to do the TM replacement. */
491 DECL_UNINLINABLE (from) = 1;
493 if (tm_wrap_map == NULL)
494 tm_wrap_map = hash_table<tm_wrapper_hasher>::create_ggc (32);
496 h = ggc_alloc<tree_map> ();
497 h->hash = htab_hash_pointer (from);
498 h->base.from = from;
499 h->to = to;
501 slot = tm_wrap_map->find_slot_with_hash (h, h->hash, INSERT);
502 *slot = h;
505 /* Return a TM-aware replacement function for DECL. */
507 static tree
508 find_tm_replacement_function (tree fndecl)
510 if (tm_wrap_map)
512 struct tree_map *h, in;
514 in.base.from = fndecl;
515 in.hash = htab_hash_pointer (fndecl);
516 h = tm_wrap_map->find_with_hash (&in, in.hash);
517 if (h)
518 return h->to;
521 /* ??? We may well want TM versions of most of the common <string.h>
522 functions. For now, we've already these two defined. */
523 /* Adjust expand_call_tm() attributes as necessary for the cases
524 handled here: */
525 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
526 switch (DECL_FUNCTION_CODE (fndecl))
528 case BUILT_IN_MEMCPY:
529 return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
530 case BUILT_IN_MEMMOVE:
531 return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
532 case BUILT_IN_MEMSET:
533 return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
534 default:
535 return NULL;
538 return NULL;
541 /* When appropriate, record TM replacement for memory allocation functions.
543 FROM is the FNDECL to wrap. */
544 void
545 tm_malloc_replacement (tree from)
547 const char *str;
548 tree to;
550 if (TREE_CODE (from) != FUNCTION_DECL)
551 return;
553 /* If we have a previous replacement, the user must be explicitly
554 wrapping malloc/calloc/free. They better know what they're
555 doing... */
556 if (find_tm_replacement_function (from))
557 return;
559 str = IDENTIFIER_POINTER (DECL_NAME (from));
561 if (!strcmp (str, "malloc"))
562 to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
563 else if (!strcmp (str, "calloc"))
564 to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
565 else if (!strcmp (str, "free"))
566 to = builtin_decl_explicit (BUILT_IN_TM_FREE);
567 else
568 return;
570 TREE_NOTHROW (to) = 0;
572 record_tm_replacement (from, to);
575 /* Diagnostics for tm_safe functions/regions. Called by the front end
576 once we've lowered the function to high-gimple. */
578 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
579 Process exactly one statement. WI->INFO is set to non-null when in
580 the context of a tm_safe function, and null for a __transaction block. */
582 #define DIAG_TM_OUTER 1
583 #define DIAG_TM_SAFE 2
584 #define DIAG_TM_RELAXED 4
586 struct diagnose_tm
588 unsigned int summary_flags : 8;
589 unsigned int block_flags : 8;
590 unsigned int func_flags : 8;
591 unsigned int saw_volatile : 1;
592 gimple stmt;
595 /* Return true if T is a volatile variable of some kind. */
597 static bool
598 volatile_var_p (tree t)
600 return (SSA_VAR_P (t)
601 && TREE_THIS_VOLATILE (TREE_TYPE (t)));
604 /* Tree callback function for diagnose_tm pass. */
606 static tree
607 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
608 void *data)
610 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
611 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
613 if (volatile_var_p (*tp)
614 && d->block_flags & DIAG_TM_SAFE
615 && !d->saw_volatile)
617 d->saw_volatile = 1;
618 error_at (gimple_location (d->stmt),
619 "invalid volatile use of %qD inside transaction",
620 *tp);
623 return NULL_TREE;
626 static inline bool
627 is_tm_safe_or_pure (const_tree x)
629 return is_tm_safe (x) || is_tm_pure (x);
632 static tree
633 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
634 struct walk_stmt_info *wi)
636 gimple stmt = gsi_stmt (*gsi);
637 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
639 /* Save stmt for use in leaf analysis. */
640 d->stmt = stmt;
642 switch (gimple_code (stmt))
644 case GIMPLE_CALL:
646 tree fn = gimple_call_fn (stmt);
648 if ((d->summary_flags & DIAG_TM_OUTER) == 0
649 && is_tm_may_cancel_outer (fn))
650 error_at (gimple_location (stmt),
651 "%<transaction_may_cancel_outer%> function call not within"
652 " outer transaction or %<transaction_may_cancel_outer%>");
654 if (d->summary_flags & DIAG_TM_SAFE)
656 bool is_safe, direct_call_p;
657 tree replacement;
659 if (TREE_CODE (fn) == ADDR_EXPR
660 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
662 direct_call_p = true;
663 replacement = TREE_OPERAND (fn, 0);
664 replacement = find_tm_replacement_function (replacement);
665 if (replacement)
666 fn = replacement;
668 else
670 direct_call_p = false;
671 replacement = NULL_TREE;
674 if (is_tm_safe_or_pure (fn))
675 is_safe = true;
676 else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
678 /* A function explicitly marked transaction_callable as
679 opposed to transaction_safe is being defined to be
680 unsafe as part of its ABI, regardless of its contents. */
681 is_safe = false;
683 else if (direct_call_p)
685 if (IS_TYPE_OR_DECL_P (fn)
686 && flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
687 is_safe = true;
688 else if (replacement)
690 /* ??? At present we've been considering replacements
691 merely transaction_callable, and therefore might
692 enter irrevocable. The tm_wrap attribute has not
693 yet made it into the new language spec. */
694 is_safe = false;
696 else
698 /* ??? Diagnostics for unmarked direct calls moved into
699 the IPA pass. Section 3.2 of the spec details how
700 functions not marked should be considered "implicitly
701 safe" based on having examined the function body. */
702 is_safe = true;
705 else
707 /* An unmarked indirect call. Consider it unsafe even
708 though optimization may yet figure out how to inline. */
709 is_safe = false;
712 if (!is_safe)
714 if (TREE_CODE (fn) == ADDR_EXPR)
715 fn = TREE_OPERAND (fn, 0);
716 if (d->block_flags & DIAG_TM_SAFE)
718 if (direct_call_p)
719 error_at (gimple_location (stmt),
720 "unsafe function call %qD within "
721 "atomic transaction", fn);
722 else
724 if (!DECL_P (fn) || DECL_NAME (fn))
725 error_at (gimple_location (stmt),
726 "unsafe function call %qE within "
727 "atomic transaction", fn);
728 else
729 error_at (gimple_location (stmt),
730 "unsafe indirect function call within "
731 "atomic transaction");
734 else
736 if (direct_call_p)
737 error_at (gimple_location (stmt),
738 "unsafe function call %qD within "
739 "%<transaction_safe%> function", fn);
740 else
742 if (!DECL_P (fn) || DECL_NAME (fn))
743 error_at (gimple_location (stmt),
744 "unsafe function call %qE within "
745 "%<transaction_safe%> function", fn);
746 else
747 error_at (gimple_location (stmt),
748 "unsafe indirect function call within "
749 "%<transaction_safe%> function");
755 break;
757 case GIMPLE_ASM:
758 /* ??? We ought to come up with a way to add attributes to
759 asm statements, and then add "transaction_safe" to it.
760 Either that or get the language spec to resurrect __tm_waiver. */
761 if (d->block_flags & DIAG_TM_SAFE)
762 error_at (gimple_location (stmt),
763 "asm not allowed in atomic transaction");
764 else if (d->func_flags & DIAG_TM_SAFE)
765 error_at (gimple_location (stmt),
766 "asm not allowed in %<transaction_safe%> function");
767 break;
769 case GIMPLE_TRANSACTION:
771 gtransaction *trans_stmt = as_a <gtransaction *> (stmt);
772 unsigned char inner_flags = DIAG_TM_SAFE;
774 if (gimple_transaction_subcode (trans_stmt) & GTMA_IS_RELAXED)
776 if (d->block_flags & DIAG_TM_SAFE)
777 error_at (gimple_location (stmt),
778 "relaxed transaction in atomic transaction");
779 else if (d->func_flags & DIAG_TM_SAFE)
780 error_at (gimple_location (stmt),
781 "relaxed transaction in %<transaction_safe%> function");
782 inner_flags = DIAG_TM_RELAXED;
784 else if (gimple_transaction_subcode (trans_stmt) & GTMA_IS_OUTER)
786 if (d->block_flags)
787 error_at (gimple_location (stmt),
788 "outer transaction in transaction");
789 else if (d->func_flags & DIAG_TM_OUTER)
790 error_at (gimple_location (stmt),
791 "outer transaction in "
792 "%<transaction_may_cancel_outer%> function");
793 else if (d->func_flags & DIAG_TM_SAFE)
794 error_at (gimple_location (stmt),
795 "outer transaction in %<transaction_safe%> function");
796 inner_flags |= DIAG_TM_OUTER;
799 *handled_ops_p = true;
800 if (gimple_transaction_body (trans_stmt))
802 struct walk_stmt_info wi_inner;
803 struct diagnose_tm d_inner;
805 memset (&d_inner, 0, sizeof (d_inner));
806 d_inner.func_flags = d->func_flags;
807 d_inner.block_flags = d->block_flags | inner_flags;
808 d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
810 memset (&wi_inner, 0, sizeof (wi_inner));
811 wi_inner.info = &d_inner;
813 walk_gimple_seq (gimple_transaction_body (trans_stmt),
814 diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
817 break;
819 default:
820 break;
823 return NULL_TREE;
826 static unsigned int
827 diagnose_tm_blocks (void)
829 struct walk_stmt_info wi;
830 struct diagnose_tm d;
832 memset (&d, 0, sizeof (d));
833 if (is_tm_may_cancel_outer (current_function_decl))
834 d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
835 else if (is_tm_safe (current_function_decl))
836 d.func_flags = DIAG_TM_SAFE;
837 d.summary_flags = d.func_flags;
839 memset (&wi, 0, sizeof (wi));
840 wi.info = &d;
842 walk_gimple_seq (gimple_body (current_function_decl),
843 diagnose_tm_1, diagnose_tm_1_op, &wi);
845 return 0;
848 static const pass_data pass_data_diagnose_tm_blocks =
850 GIMPLE_PASS, /* type */
851 "*diagnose_tm_blocks", /* name */
852 OPTGROUP_NONE, /* optinfo_flags */
853 TV_TRANS_MEM, /* tv_id */
854 PROP_gimple_any, /* properties_required */
855 0, /* properties_provided */
856 0, /* properties_destroyed */
857 0, /* todo_flags_start */
858 0, /* todo_flags_finish */
861 class pass_diagnose_tm_blocks GCC_FINAL : public gimple_opt_pass
863 public:
864 pass_diagnose_tm_blocks (gcc::context *ctxt)
865 : gimple_opt_pass (pass_data_diagnose_tm_blocks, ctxt)
868 /* opt_pass methods: */
869 virtual bool gate (function *) { return flag_tm; }
870 virtual unsigned int execute (function *) { return diagnose_tm_blocks (); }
872 }; // class pass_diagnose_tm_blocks
874 gimple_opt_pass *
875 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
877 return new pass_diagnose_tm_blocks (ctxt);
880 /* Instead of instrumenting thread private memory, we save the
881 addresses in a log which we later use to save/restore the addresses
882 upon transaction start/restart.
884 The log is keyed by address, where each element contains individual
885 statements among different code paths that perform the store.
887 This log is later used to generate either plain save/restore of the
888 addresses upon transaction start/restart, or calls to the ITM_L*
889 logging functions.
891 So for something like:
893 struct large { int x[1000]; };
894 struct large lala = { 0 };
895 __transaction {
896 lala.x[i] = 123;
900 We can either save/restore:
902 lala = { 0 };
903 trxn = _ITM_startTransaction ();
904 if (trxn & a_saveLiveVariables)
905 tmp_lala1 = lala.x[i];
906 else if (a & a_restoreLiveVariables)
907 lala.x[i] = tmp_lala1;
909 or use the logging functions:
911 lala = { 0 };
912 trxn = _ITM_startTransaction ();
913 _ITM_LU4 (&lala.x[i]);
915 Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
916 far up the dominator tree to shadow all of the writes to a given
917 location (thus reducing the total number of logging calls), but not
918 so high as to be called on a path that does not perform a
919 write. */
921 /* One individual log entry. We may have multiple statements for the
922 same location if neither dominate each other (on different
923 execution paths). */
924 typedef struct tm_log_entry
926 /* Address to save. */
927 tree addr;
928 /* Entry block for the transaction this address occurs in. */
929 basic_block entry_block;
930 /* Dominating statements the store occurs in. */
931 vec<gimple> stmts;
932 /* Initially, while we are building the log, we place a nonzero
933 value here to mean that this address *will* be saved with a
934 save/restore sequence. Later, when generating the save sequence
935 we place the SSA temp generated here. */
936 tree save_var;
937 } *tm_log_entry_t;
940 /* Log entry hashtable helpers. */
942 struct log_entry_hasher : pointer_hash <tm_log_entry>
944 static inline hashval_t hash (const tm_log_entry *);
945 static inline bool equal (const tm_log_entry *, const tm_log_entry *);
946 static inline void remove (tm_log_entry *);
949 /* Htab support. Return hash value for a `tm_log_entry'. */
950 inline hashval_t
951 log_entry_hasher::hash (const tm_log_entry *log)
953 return iterative_hash_expr (log->addr, 0);
956 /* Htab support. Return true if two log entries are the same. */
957 inline bool
958 log_entry_hasher::equal (const tm_log_entry *log1, const tm_log_entry *log2)
960 /* FIXME:
962 rth: I suggest that we get rid of the component refs etc.
963 I.e. resolve the reference to base + offset.
965 We may need to actually finish a merge with mainline for this,
966 since we'd like to be presented with Richi's MEM_REF_EXPRs more
967 often than not. But in the meantime your tm_log_entry could save
968 the results of get_inner_reference.
970 See: g++.dg/tm/pr46653.C
973 /* Special case plain equality because operand_equal_p() below will
974 return FALSE if the addresses are equal but they have
975 side-effects (e.g. a volatile address). */
976 if (log1->addr == log2->addr)
977 return true;
979 return operand_equal_p (log1->addr, log2->addr, 0);
982 /* Htab support. Free one tm_log_entry. */
983 inline void
984 log_entry_hasher::remove (tm_log_entry *lp)
986 lp->stmts.release ();
987 free (lp);
991 /* The actual log. */
992 static hash_table<log_entry_hasher> *tm_log;
994 /* Addresses to log with a save/restore sequence. These should be in
995 dominator order. */
996 static vec<tree> tm_log_save_addresses;
998 enum thread_memory_type
1000 mem_non_local = 0,
1001 mem_thread_local,
1002 mem_transaction_local,
1003 mem_max
1006 typedef struct tm_new_mem_map
1008 /* SSA_NAME being dereferenced. */
1009 tree val;
1010 enum thread_memory_type local_new_memory;
1011 } tm_new_mem_map_t;
1013 /* Hashtable helpers. */
1015 struct tm_mem_map_hasher : free_ptr_hash <tm_new_mem_map_t>
1017 static inline hashval_t hash (const tm_new_mem_map_t *);
1018 static inline bool equal (const tm_new_mem_map_t *, const tm_new_mem_map_t *);
1021 inline hashval_t
1022 tm_mem_map_hasher::hash (const tm_new_mem_map_t *v)
1024 return (intptr_t)v->val >> 4;
1027 inline bool
1028 tm_mem_map_hasher::equal (const tm_new_mem_map_t *v, const tm_new_mem_map_t *c)
1030 return v->val == c->val;
1033 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1034 of memory (malloc, alloc, etc). */
1035 static hash_table<tm_mem_map_hasher> *tm_new_mem_hash;
1037 /* Initialize logging data structures. */
1038 static void
1039 tm_log_init (void)
1041 tm_log = new hash_table<log_entry_hasher> (10);
1042 tm_new_mem_hash = new hash_table<tm_mem_map_hasher> (5);
1043 tm_log_save_addresses.create (5);
1046 /* Free logging data structures. */
1047 static void
1048 tm_log_delete (void)
1050 delete tm_log;
1051 tm_log = NULL;
1052 delete tm_new_mem_hash;
1053 tm_new_mem_hash = NULL;
1054 tm_log_save_addresses.release ();
1057 /* Return true if MEM is a transaction invariant memory for the TM
1058 region starting at REGION_ENTRY_BLOCK. */
1059 static bool
1060 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1062 if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1063 && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1065 basic_block def_bb;
1067 def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1068 return def_bb != region_entry_block
1069 && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1072 mem = strip_invariant_refs (mem);
1073 return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1076 /* Given an address ADDR in STMT, find it in the memory log or add it,
1077 making sure to keep only the addresses highest in the dominator
1078 tree.
1080 ENTRY_BLOCK is the entry_block for the transaction.
1082 If we find the address in the log, make sure it's either the same
1083 address, or an equivalent one that dominates ADDR.
1085 If we find the address, but neither ADDR dominates the found
1086 address, nor the found one dominates ADDR, we're on different
1087 execution paths. Add it.
1089 If known, ENTRY_BLOCK is the entry block for the region, otherwise
1090 NULL. */
1091 static void
1092 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1094 tm_log_entry **slot;
1095 struct tm_log_entry l, *lp;
1097 l.addr = addr;
1098 slot = tm_log->find_slot (&l, INSERT);
1099 if (!*slot)
1101 tree type = TREE_TYPE (addr);
1103 lp = XNEW (struct tm_log_entry);
1104 lp->addr = addr;
1105 *slot = lp;
1107 /* Small invariant addresses can be handled as save/restores. */
1108 if (entry_block
1109 && transaction_invariant_address_p (lp->addr, entry_block)
1110 && TYPE_SIZE_UNIT (type) != NULL
1111 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
1112 && ((HOST_WIDE_INT) tree_to_uhwi (TYPE_SIZE_UNIT (type))
1113 < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1114 /* We must be able to copy this type normally. I.e., no
1115 special constructors and the like. */
1116 && !TREE_ADDRESSABLE (type))
1118 lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1119 lp->stmts.create (0);
1120 lp->entry_block = entry_block;
1121 /* Save addresses separately in dominator order so we don't
1122 get confused by overlapping addresses in the save/restore
1123 sequence. */
1124 tm_log_save_addresses.safe_push (lp->addr);
1126 else
1128 /* Use the logging functions. */
1129 lp->stmts.create (5);
1130 lp->stmts.quick_push (stmt);
1131 lp->save_var = NULL;
1134 else
1136 size_t i;
1137 gimple oldstmt;
1139 lp = *slot;
1141 /* If we're generating a save/restore sequence, we don't care
1142 about statements. */
1143 if (lp->save_var)
1144 return;
1146 for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1148 if (stmt == oldstmt)
1149 return;
1150 /* We already have a store to the same address, higher up the
1151 dominator tree. Nothing to do. */
1152 if (dominated_by_p (CDI_DOMINATORS,
1153 gimple_bb (stmt), gimple_bb (oldstmt)))
1154 return;
1155 /* We should be processing blocks in dominator tree order. */
1156 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1157 gimple_bb (oldstmt), gimple_bb (stmt)));
1159 /* Store is on a different code path. */
1160 lp->stmts.safe_push (stmt);
1164 /* Gimplify the address of a TARGET_MEM_REF. Return the SSA_NAME
1165 result, insert the new statements before GSI. */
1167 static tree
1168 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1170 if (TREE_CODE (x) == TARGET_MEM_REF)
1171 x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1172 else
1173 x = build_fold_addr_expr (x);
1174 return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1177 /* Instrument one address with the logging functions.
1178 ADDR is the address to save.
1179 STMT is the statement before which to place it. */
1180 static void
1181 tm_log_emit_stmt (tree addr, gimple stmt)
1183 tree type = TREE_TYPE (addr);
1184 tree size = TYPE_SIZE_UNIT (type);
1185 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1186 gimple log;
1187 enum built_in_function code = BUILT_IN_TM_LOG;
1189 if (type == float_type_node)
1190 code = BUILT_IN_TM_LOG_FLOAT;
1191 else if (type == double_type_node)
1192 code = BUILT_IN_TM_LOG_DOUBLE;
1193 else if (type == long_double_type_node)
1194 code = BUILT_IN_TM_LOG_LDOUBLE;
1195 else if (tree_fits_uhwi_p (size))
1197 unsigned int n = tree_to_uhwi (size);
1198 switch (n)
1200 case 1:
1201 code = BUILT_IN_TM_LOG_1;
1202 break;
1203 case 2:
1204 code = BUILT_IN_TM_LOG_2;
1205 break;
1206 case 4:
1207 code = BUILT_IN_TM_LOG_4;
1208 break;
1209 case 8:
1210 code = BUILT_IN_TM_LOG_8;
1211 break;
1212 default:
1213 code = BUILT_IN_TM_LOG;
1214 if (TREE_CODE (type) == VECTOR_TYPE)
1216 if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1217 code = BUILT_IN_TM_LOG_M64;
1218 else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1219 code = BUILT_IN_TM_LOG_M128;
1220 else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1221 code = BUILT_IN_TM_LOG_M256;
1223 break;
1227 addr = gimplify_addr (&gsi, addr);
1228 if (code == BUILT_IN_TM_LOG)
1229 log = gimple_build_call (builtin_decl_explicit (code), 2, addr, size);
1230 else
1231 log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1232 gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1235 /* Go through the log and instrument address that must be instrumented
1236 with the logging functions. Leave the save/restore addresses for
1237 later. */
1238 static void
1239 tm_log_emit (void)
1241 hash_table<log_entry_hasher>::iterator hi;
1242 struct tm_log_entry *lp;
1244 FOR_EACH_HASH_TABLE_ELEMENT (*tm_log, lp, tm_log_entry_t, hi)
1246 size_t i;
1247 gimple stmt;
1249 if (dump_file)
1251 fprintf (dump_file, "TM thread private mem logging: ");
1252 print_generic_expr (dump_file, lp->addr, 0);
1253 fprintf (dump_file, "\n");
1256 if (lp->save_var)
1258 if (dump_file)
1259 fprintf (dump_file, "DUMPING to variable\n");
1260 continue;
1262 else
1264 if (dump_file)
1265 fprintf (dump_file, "DUMPING with logging functions\n");
1266 for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1267 tm_log_emit_stmt (lp->addr, stmt);
1272 /* Emit the save sequence for the corresponding addresses in the log.
1273 ENTRY_BLOCK is the entry block for the transaction.
1274 BB is the basic block to insert the code in. */
1275 static void
1276 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1278 size_t i;
1279 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1280 gimple stmt;
1281 struct tm_log_entry l, *lp;
1283 for (i = 0; i < tm_log_save_addresses.length (); ++i)
1285 l.addr = tm_log_save_addresses[i];
1286 lp = *(tm_log->find_slot (&l, NO_INSERT));
1287 gcc_assert (lp->save_var != NULL);
1289 /* We only care about variables in the current transaction. */
1290 if (lp->entry_block != entry_block)
1291 continue;
1293 stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1295 /* Make sure we can create an SSA_NAME for this type. For
1296 instance, aggregates aren't allowed, in which case the system
1297 will create a VOP for us and everything will just work. */
1298 if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1300 lp->save_var = make_ssa_name (lp->save_var, stmt);
1301 gimple_assign_set_lhs (stmt, lp->save_var);
1304 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1308 /* Emit the restore sequence for the corresponding addresses in the log.
1309 ENTRY_BLOCK is the entry block for the transaction.
1310 BB is the basic block to insert the code in. */
1311 static void
1312 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1314 int i;
1315 struct tm_log_entry l, *lp;
1316 gimple_stmt_iterator gsi;
1317 gimple stmt;
1319 for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1321 l.addr = tm_log_save_addresses[i];
1322 lp = *(tm_log->find_slot (&l, NO_INSERT));
1323 gcc_assert (lp->save_var != NULL);
1325 /* We only care about variables in the current transaction. */
1326 if (lp->entry_block != entry_block)
1327 continue;
1329 /* Restores are in LIFO order from the saves in case we have
1330 overlaps. */
1331 gsi = gsi_start_bb (bb);
1333 stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1334 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1339 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1340 struct walk_stmt_info *);
1341 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1342 struct walk_stmt_info *);
1344 /* Evaluate an address X being dereferenced and determine if it
1345 originally points to a non aliased new chunk of memory (malloc,
1346 alloca, etc).
1348 Return MEM_THREAD_LOCAL if it points to a thread-local address.
1349 Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1350 Return MEM_NON_LOCAL otherwise.
1352 ENTRY_BLOCK is the entry block to the transaction containing the
1353 dereference of X. */
1354 static enum thread_memory_type
1355 thread_private_new_memory (basic_block entry_block, tree x)
1357 gimple stmt = NULL;
1358 enum tree_code code;
1359 tm_new_mem_map_t **slot;
1360 tm_new_mem_map_t elt, *elt_p;
1361 tree val = x;
1362 enum thread_memory_type retval = mem_transaction_local;
1364 if (!entry_block
1365 || TREE_CODE (x) != SSA_NAME
1366 /* Possible uninitialized use, or a function argument. In
1367 either case, we don't care. */
1368 || SSA_NAME_IS_DEFAULT_DEF (x))
1369 return mem_non_local;
1371 /* Look in cache first. */
1372 elt.val = x;
1373 slot = tm_new_mem_hash->find_slot (&elt, INSERT);
1374 elt_p = *slot;
1375 if (elt_p)
1376 return elt_p->local_new_memory;
1378 /* Optimistically assume the memory is transaction local during
1379 processing. This catches recursion into this variable. */
1380 *slot = elt_p = XNEW (tm_new_mem_map_t);
1381 elt_p->val = val;
1382 elt_p->local_new_memory = mem_transaction_local;
1384 /* Search DEF chain to find the original definition of this address. */
1387 if (ptr_deref_may_alias_global_p (x))
1389 /* Address escapes. This is not thread-private. */
1390 retval = mem_non_local;
1391 goto new_memory_ret;
1394 stmt = SSA_NAME_DEF_STMT (x);
1396 /* If the malloc call is outside the transaction, this is
1397 thread-local. */
1398 if (retval != mem_thread_local
1399 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1400 retval = mem_thread_local;
1402 if (is_gimple_assign (stmt))
1404 code = gimple_assign_rhs_code (stmt);
1405 /* x = foo ==> foo */
1406 if (code == SSA_NAME)
1407 x = gimple_assign_rhs1 (stmt);
1408 /* x = foo + n ==> foo */
1409 else if (code == POINTER_PLUS_EXPR)
1410 x = gimple_assign_rhs1 (stmt);
1411 /* x = (cast*) foo ==> foo */
1412 else if (code == VIEW_CONVERT_EXPR || CONVERT_EXPR_CODE_P (code))
1413 x = gimple_assign_rhs1 (stmt);
1414 /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1415 else if (code == COND_EXPR)
1417 tree op1 = gimple_assign_rhs2 (stmt);
1418 tree op2 = gimple_assign_rhs3 (stmt);
1419 enum thread_memory_type mem;
1420 retval = thread_private_new_memory (entry_block, op1);
1421 if (retval == mem_non_local)
1422 goto new_memory_ret;
1423 mem = thread_private_new_memory (entry_block, op2);
1424 retval = MIN (retval, mem);
1425 goto new_memory_ret;
1427 else
1429 retval = mem_non_local;
1430 goto new_memory_ret;
1433 else
1435 if (gimple_code (stmt) == GIMPLE_PHI)
1437 unsigned int i;
1438 enum thread_memory_type mem;
1439 tree phi_result = gimple_phi_result (stmt);
1441 /* If any of the ancestors are non-local, we are sure to
1442 be non-local. Otherwise we can avoid doing anything
1443 and inherit what has already been generated. */
1444 retval = mem_max;
1445 for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1447 tree op = PHI_ARG_DEF (stmt, i);
1449 /* Exclude self-assignment. */
1450 if (phi_result == op)
1451 continue;
1453 mem = thread_private_new_memory (entry_block, op);
1454 if (mem == mem_non_local)
1456 retval = mem;
1457 goto new_memory_ret;
1459 retval = MIN (retval, mem);
1461 goto new_memory_ret;
1463 break;
1466 while (TREE_CODE (x) == SSA_NAME);
1468 if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1469 /* Thread-local or transaction-local. */
1471 else
1472 retval = mem_non_local;
1474 new_memory_ret:
1475 elt_p->local_new_memory = retval;
1476 return retval;
1479 /* Determine whether X has to be instrumented using a read
1480 or write barrier.
1482 ENTRY_BLOCK is the entry block for the region where stmt resides
1483 in. NULL if unknown.
1485 STMT is the statement in which X occurs in. It is used for thread
1486 private memory instrumentation. If no TPM instrumentation is
1487 desired, STMT should be null. */
1488 static bool
1489 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1491 tree orig = x;
1492 while (handled_component_p (x))
1493 x = TREE_OPERAND (x, 0);
1495 switch (TREE_CODE (x))
1497 case INDIRECT_REF:
1498 case MEM_REF:
1500 enum thread_memory_type ret;
1502 ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1503 if (ret == mem_non_local)
1504 return true;
1505 if (stmt && ret == mem_thread_local)
1506 /* ?? Should we pass `orig', or the INDIRECT_REF X. ?? */
1507 tm_log_add (entry_block, orig, stmt);
1509 /* Transaction-locals require nothing at all. For malloc, a
1510 transaction restart frees the memory and we reallocate.
1511 For alloca, the stack pointer gets reset by the retry and
1512 we reallocate. */
1513 return false;
1516 case TARGET_MEM_REF:
1517 if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1518 return true;
1519 x = TREE_OPERAND (TMR_BASE (x), 0);
1520 if (TREE_CODE (x) == PARM_DECL)
1521 return false;
1522 gcc_assert (TREE_CODE (x) == VAR_DECL);
1523 /* FALLTHRU */
1525 case PARM_DECL:
1526 case RESULT_DECL:
1527 case VAR_DECL:
1528 if (DECL_BY_REFERENCE (x))
1530 /* ??? This value is a pointer, but aggregate_value_p has been
1531 jigged to return true which confuses needs_to_live_in_memory.
1532 This ought to be cleaned up generically.
1534 FIXME: Verify this still happens after the next mainline
1535 merge. Testcase ie g++.dg/tm/pr47554.C.
1537 return false;
1540 if (is_global_var (x))
1541 return !TREE_READONLY (x);
1542 if (/* FIXME: This condition should actually go below in the
1543 tm_log_add() call, however is_call_clobbered() depends on
1544 aliasing info which is not available during
1545 gimplification. Since requires_barrier() gets called
1546 during lower_sequence_tm/gimplification, leave the call
1547 to needs_to_live_in_memory until we eliminate
1548 lower_sequence_tm altogether. */
1549 needs_to_live_in_memory (x))
1550 return true;
1551 else
1553 /* For local memory that doesn't escape (aka thread private
1554 memory), we can either save the value at the beginning of
1555 the transaction and restore on restart, or call a tm
1556 function to dynamically save and restore on restart
1557 (ITM_L*). */
1558 if (stmt)
1559 tm_log_add (entry_block, orig, stmt);
1560 return false;
1563 default:
1564 return false;
1568 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1569 a transaction region. */
1571 static void
1572 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1574 gimple stmt = gsi_stmt (*gsi);
1576 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1577 *state |= GTMA_HAVE_LOAD;
1578 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1579 *state |= GTMA_HAVE_STORE;
1582 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction. */
1584 static void
1585 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1587 gimple stmt = gsi_stmt (*gsi);
1588 tree fn;
1590 if (is_tm_pure_call (stmt))
1591 return;
1593 /* Check if this call is a transaction abort. */
1594 fn = gimple_call_fndecl (stmt);
1595 if (is_tm_abort (fn))
1596 *state |= GTMA_HAVE_ABORT;
1598 /* Note that something may happen. */
1599 *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1602 /* Lower a GIMPLE_TRANSACTION statement. */
1604 static void
1605 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1607 gimple g;
1608 gtransaction *stmt = as_a <gtransaction *> (gsi_stmt (*gsi));
1609 unsigned int *outer_state = (unsigned int *) wi->info;
1610 unsigned int this_state = 0;
1611 struct walk_stmt_info this_wi;
1613 /* First, lower the body. The scanning that we do inside gives
1614 us some idea of what we're dealing with. */
1615 memset (&this_wi, 0, sizeof (this_wi));
1616 this_wi.info = (void *) &this_state;
1617 walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1618 lower_sequence_tm, NULL, &this_wi);
1620 /* If there was absolutely nothing transaction related inside the
1621 transaction, we may elide it. Likewise if this is a nested
1622 transaction and does not contain an abort. */
1623 if (this_state == 0
1624 || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1626 if (outer_state)
1627 *outer_state |= this_state;
1629 gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1630 GSI_SAME_STMT);
1631 gimple_transaction_set_body (stmt, NULL);
1633 gsi_remove (gsi, true);
1634 wi->removed_stmt = true;
1635 return;
1638 /* Wrap the body of the transaction in a try-finally node so that
1639 the commit call is always properly called. */
1640 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1641 if (flag_exceptions)
1643 tree ptr;
1644 gimple_seq n_seq, e_seq;
1646 n_seq = gimple_seq_alloc_with_stmt (g);
1647 e_seq = NULL;
1649 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1650 1, integer_zero_node);
1651 ptr = create_tmp_var (ptr_type_node);
1652 gimple_call_set_lhs (g, ptr);
1653 gimple_seq_add_stmt (&e_seq, g);
1655 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1656 1, ptr);
1657 gimple_seq_add_stmt (&e_seq, g);
1659 g = gimple_build_eh_else (n_seq, e_seq);
1662 g = gimple_build_try (gimple_transaction_body (stmt),
1663 gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1664 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1666 gimple_transaction_set_body (stmt, NULL);
1668 /* If the transaction calls abort or if this is an outer transaction,
1669 add an "over" label afterwards. */
1670 if ((this_state & (GTMA_HAVE_ABORT))
1671 || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1673 tree label = create_artificial_label (UNKNOWN_LOCATION);
1674 gimple_transaction_set_label (stmt, label);
1675 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1678 /* Record the set of operations found for use later. */
1679 this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1680 gimple_transaction_set_subcode (stmt, this_state);
1683 /* Iterate through the statements in the sequence, lowering them all
1684 as appropriate for being in a transaction. */
1686 static tree
1687 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1688 struct walk_stmt_info *wi)
1690 unsigned int *state = (unsigned int *) wi->info;
1691 gimple stmt = gsi_stmt (*gsi);
1693 *handled_ops_p = true;
1694 switch (gimple_code (stmt))
1696 case GIMPLE_ASSIGN:
1697 /* Only memory reads/writes need to be instrumented. */
1698 if (gimple_assign_single_p (stmt))
1699 examine_assign_tm (state, gsi);
1700 break;
1702 case GIMPLE_CALL:
1703 examine_call_tm (state, gsi);
1704 break;
1706 case GIMPLE_ASM:
1707 *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1708 break;
1710 case GIMPLE_TRANSACTION:
1711 lower_transaction (gsi, wi);
1712 break;
1714 default:
1715 *handled_ops_p = !gimple_has_substatements (stmt);
1716 break;
1719 return NULL_TREE;
1722 /* Iterate through the statements in the sequence, lowering them all
1723 as appropriate for being outside of a transaction. */
1725 static tree
1726 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1727 struct walk_stmt_info * wi)
1729 gimple stmt = gsi_stmt (*gsi);
1731 if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1733 *handled_ops_p = true;
1734 lower_transaction (gsi, wi);
1736 else
1737 *handled_ops_p = !gimple_has_substatements (stmt);
1739 return NULL_TREE;
1742 /* Main entry point for flattening GIMPLE_TRANSACTION constructs. After
1743 this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1744 been moved out, and all the data required for constructing a proper
1745 CFG has been recorded. */
1747 static unsigned int
1748 execute_lower_tm (void)
1750 struct walk_stmt_info wi;
1751 gimple_seq body;
1753 /* Transactional clones aren't created until a later pass. */
1754 gcc_assert (!decl_is_tm_clone (current_function_decl));
1756 body = gimple_body (current_function_decl);
1757 memset (&wi, 0, sizeof (wi));
1758 walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1759 gimple_set_body (current_function_decl, body);
1761 return 0;
1764 static const pass_data pass_data_lower_tm =
1766 GIMPLE_PASS, /* type */
1767 "tmlower", /* name */
1768 OPTGROUP_NONE, /* optinfo_flags */
1769 TV_TRANS_MEM, /* tv_id */
1770 PROP_gimple_lcf, /* properties_required */
1771 0, /* properties_provided */
1772 0, /* properties_destroyed */
1773 0, /* todo_flags_start */
1774 0, /* todo_flags_finish */
1777 class pass_lower_tm GCC_FINAL : public gimple_opt_pass
1779 public:
1780 pass_lower_tm (gcc::context *ctxt)
1781 : gimple_opt_pass (pass_data_lower_tm, ctxt)
1784 /* opt_pass methods: */
1785 virtual bool gate (function *) { return flag_tm; }
1786 virtual unsigned int execute (function *) { return execute_lower_tm (); }
1788 }; // class pass_lower_tm
1790 gimple_opt_pass *
1791 make_pass_lower_tm (gcc::context *ctxt)
1793 return new pass_lower_tm (ctxt);
1796 /* Collect region information for each transaction. */
1798 struct tm_region
1800 public:
1802 /* The field "transaction_stmt" is initially a gtransaction *,
1803 but eventually gets lowered to a gcall *(to BUILT_IN_TM_START).
1805 Helper method to get it as a gtransaction *, with code-checking
1806 in a checked-build. */
1808 gtransaction *
1809 get_transaction_stmt () const
1811 return as_a <gtransaction *> (transaction_stmt);
1814 public:
1816 /* Link to the next unnested transaction. */
1817 struct tm_region *next;
1819 /* Link to the next inner transaction. */
1820 struct tm_region *inner;
1822 /* Link to the next outer transaction. */
1823 struct tm_region *outer;
1825 /* The GIMPLE_TRANSACTION statement beginning this transaction.
1826 After TM_MARK, this gets replaced by a call to
1827 BUILT_IN_TM_START.
1828 Hence this will be either a gtransaction *or a gcall *. */
1829 gimple transaction_stmt;
1831 /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1832 BUILT_IN_TM_START, this field is true if the transaction is an
1833 outer transaction. */
1834 bool original_transaction_was_outer;
1836 /* Return value from BUILT_IN_TM_START. */
1837 tree tm_state;
1839 /* The entry block to this region. This will always be the first
1840 block of the body of the transaction. */
1841 basic_block entry_block;
1843 /* The first block after an expanded call to _ITM_beginTransaction. */
1844 basic_block restart_block;
1846 /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1847 These blocks are still a part of the region (i.e., the border is
1848 inclusive). Note that this set is only complete for paths in the CFG
1849 starting at ENTRY_BLOCK, and that there is no exit block recorded for
1850 the edge to the "over" label. */
1851 bitmap exit_blocks;
1853 /* The set of all blocks that have an TM_IRREVOCABLE call. */
1854 bitmap irr_blocks;
1857 typedef struct tm_region *tm_region_p;
1859 /* True if there are pending edge statements to be committed for the
1860 current function being scanned in the tmmark pass. */
1861 bool pending_edge_inserts_p;
1863 static struct tm_region *all_tm_regions;
1864 static bitmap_obstack tm_obstack;
1867 /* A subroutine of tm_region_init. Record the existence of the
1868 GIMPLE_TRANSACTION statement in a tree of tm_region elements. */
1870 static struct tm_region *
1871 tm_region_init_0 (struct tm_region *outer, basic_block bb,
1872 gtransaction *stmt)
1874 struct tm_region *region;
1876 region = (struct tm_region *)
1877 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1879 if (outer)
1881 region->next = outer->inner;
1882 outer->inner = region;
1884 else
1886 region->next = all_tm_regions;
1887 all_tm_regions = region;
1889 region->inner = NULL;
1890 region->outer = outer;
1892 region->transaction_stmt = stmt;
1893 region->original_transaction_was_outer = false;
1894 region->tm_state = NULL;
1896 /* There are either one or two edges out of the block containing
1897 the GIMPLE_TRANSACTION, one to the actual region and one to the
1898 "over" label if the region contains an abort. The former will
1899 always be the one marked FALLTHRU. */
1900 region->entry_block = FALLTHRU_EDGE (bb)->dest;
1902 region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1903 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1905 return region;
1908 /* A subroutine of tm_region_init. Record all the exit and
1909 irrevocable blocks in BB into the region's exit_blocks and
1910 irr_blocks bitmaps. Returns the new region being scanned. */
1912 static struct tm_region *
1913 tm_region_init_1 (struct tm_region *region, basic_block bb)
1915 gimple_stmt_iterator gsi;
1916 gimple g;
1918 if (!region
1919 || (!region->irr_blocks && !region->exit_blocks))
1920 return region;
1922 /* Check to see if this is the end of a region by seeing if it
1923 contains a call to __builtin_tm_commit{,_eh}. Note that the
1924 outermost region for DECL_IS_TM_CLONE need not collect this. */
1925 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1927 g = gsi_stmt (gsi);
1928 if (gimple_code (g) == GIMPLE_CALL)
1930 tree fn = gimple_call_fndecl (g);
1931 if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1933 if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1934 || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1935 && region->exit_blocks)
1937 bitmap_set_bit (region->exit_blocks, bb->index);
1938 region = region->outer;
1939 break;
1941 if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1942 bitmap_set_bit (region->irr_blocks, bb->index);
1946 return region;
1949 /* Collect all of the transaction regions within the current function
1950 and record them in ALL_TM_REGIONS. The REGION parameter may specify
1951 an "outermost" region for use by tm clones. */
1953 static void
1954 tm_region_init (struct tm_region *region)
1956 gimple g;
1957 edge_iterator ei;
1958 edge e;
1959 basic_block bb;
1960 auto_vec<basic_block> queue;
1961 bitmap visited_blocks = BITMAP_ALLOC (NULL);
1962 struct tm_region *old_region;
1963 auto_vec<tm_region_p> bb_regions;
1965 all_tm_regions = region;
1966 bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1968 /* We could store this information in bb->aux, but we may get called
1969 through get_all_tm_blocks() from another pass that may be already
1970 using bb->aux. */
1971 bb_regions.safe_grow_cleared (last_basic_block_for_fn (cfun));
1973 queue.safe_push (bb);
1974 bb_regions[bb->index] = region;
1977 bb = queue.pop ();
1978 region = bb_regions[bb->index];
1979 bb_regions[bb->index] = NULL;
1981 /* Record exit and irrevocable blocks. */
1982 region = tm_region_init_1 (region, bb);
1984 /* Check for the last statement in the block beginning a new region. */
1985 g = last_stmt (bb);
1986 old_region = region;
1987 if (g)
1988 if (gtransaction *trans_stmt = dyn_cast <gtransaction *> (g))
1989 region = tm_region_init_0 (region, bb, trans_stmt);
1991 /* Process subsequent blocks. */
1992 FOR_EACH_EDGE (e, ei, bb->succs)
1993 if (!bitmap_bit_p (visited_blocks, e->dest->index))
1995 bitmap_set_bit (visited_blocks, e->dest->index);
1996 queue.safe_push (e->dest);
1998 /* If the current block started a new region, make sure that only
1999 the entry block of the new region is associated with this region.
2000 Other successors are still part of the old region. */
2001 if (old_region != region && e->dest != region->entry_block)
2002 bb_regions[e->dest->index] = old_region;
2003 else
2004 bb_regions[e->dest->index] = region;
2007 while (!queue.is_empty ());
2008 BITMAP_FREE (visited_blocks);
2011 /* The "gate" function for all transactional memory expansion and optimization
2012 passes. We collect region information for each top-level transaction, and
2013 if we don't find any, we skip all of the TM passes. Each region will have
2014 all of the exit blocks recorded, and the originating statement. */
2016 static bool
2017 gate_tm_init (void)
2019 if (!flag_tm)
2020 return false;
2022 calculate_dominance_info (CDI_DOMINATORS);
2023 bitmap_obstack_initialize (&tm_obstack);
2025 /* If the function is a TM_CLONE, then the entire function is the region. */
2026 if (decl_is_tm_clone (current_function_decl))
2028 struct tm_region *region = (struct tm_region *)
2029 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
2030 memset (region, 0, sizeof (*region));
2031 region->entry_block = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
2032 /* For a clone, the entire function is the region. But even if
2033 we don't need to record any exit blocks, we may need to
2034 record irrevocable blocks. */
2035 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
2037 tm_region_init (region);
2039 else
2041 tm_region_init (NULL);
2043 /* If we didn't find any regions, cleanup and skip the whole tree
2044 of tm-related optimizations. */
2045 if (all_tm_regions == NULL)
2047 bitmap_obstack_release (&tm_obstack);
2048 return false;
2052 return true;
2055 static const pass_data pass_data_tm_init =
2057 GIMPLE_PASS, /* type */
2058 "*tminit", /* name */
2059 OPTGROUP_NONE, /* optinfo_flags */
2060 TV_TRANS_MEM, /* tv_id */
2061 ( PROP_ssa | PROP_cfg ), /* properties_required */
2062 0, /* properties_provided */
2063 0, /* properties_destroyed */
2064 0, /* todo_flags_start */
2065 0, /* todo_flags_finish */
2068 class pass_tm_init GCC_FINAL : public gimple_opt_pass
2070 public:
2071 pass_tm_init (gcc::context *ctxt)
2072 : gimple_opt_pass (pass_data_tm_init, ctxt)
2075 /* opt_pass methods: */
2076 virtual bool gate (function *) { return gate_tm_init (); }
2078 }; // class pass_tm_init
2080 gimple_opt_pass *
2081 make_pass_tm_init (gcc::context *ctxt)
2083 return new pass_tm_init (ctxt);
2086 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2087 represented by STATE. */
2089 static inline void
2090 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2092 if (region && region->transaction_stmt)
2094 gtransaction *transaction_stmt = region->get_transaction_stmt ();
2095 flags |= gimple_transaction_subcode (transaction_stmt);
2096 gimple_transaction_set_subcode (transaction_stmt, flags);
2100 /* Construct a memory load in a transactional context. Return the
2101 gimple statement performing the load, or NULL if there is no
2102 TM_LOAD builtin of the appropriate size to do the load.
2104 LOC is the location to use for the new statement(s). */
2106 static gcall *
2107 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2109 enum built_in_function code = END_BUILTINS;
2110 tree t, type = TREE_TYPE (rhs), decl;
2111 gcall *gcall;
2113 if (type == float_type_node)
2114 code = BUILT_IN_TM_LOAD_FLOAT;
2115 else if (type == double_type_node)
2116 code = BUILT_IN_TM_LOAD_DOUBLE;
2117 else if (type == long_double_type_node)
2118 code = BUILT_IN_TM_LOAD_LDOUBLE;
2119 else if (TYPE_SIZE_UNIT (type) != NULL
2120 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2122 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2124 case 1:
2125 code = BUILT_IN_TM_LOAD_1;
2126 break;
2127 case 2:
2128 code = BUILT_IN_TM_LOAD_2;
2129 break;
2130 case 4:
2131 code = BUILT_IN_TM_LOAD_4;
2132 break;
2133 case 8:
2134 code = BUILT_IN_TM_LOAD_8;
2135 break;
2139 if (code == END_BUILTINS)
2141 decl = targetm.vectorize.builtin_tm_load (type);
2142 if (!decl)
2143 return NULL;
2145 else
2146 decl = builtin_decl_explicit (code);
2148 t = gimplify_addr (gsi, rhs);
2149 gcall = gimple_build_call (decl, 1, t);
2150 gimple_set_location (gcall, loc);
2152 t = TREE_TYPE (TREE_TYPE (decl));
2153 if (useless_type_conversion_p (type, t))
2155 gimple_call_set_lhs (gcall, lhs);
2156 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2158 else
2160 gimple g;
2161 tree temp;
2163 temp = create_tmp_reg (t);
2164 gimple_call_set_lhs (gcall, temp);
2165 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2167 t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2168 g = gimple_build_assign (lhs, t);
2169 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2172 return gcall;
2176 /* Similarly for storing TYPE in a transactional context. */
2178 static gcall *
2179 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2181 enum built_in_function code = END_BUILTINS;
2182 tree t, fn, type = TREE_TYPE (rhs), simple_type;
2183 gcall *gcall;
2185 if (type == float_type_node)
2186 code = BUILT_IN_TM_STORE_FLOAT;
2187 else if (type == double_type_node)
2188 code = BUILT_IN_TM_STORE_DOUBLE;
2189 else if (type == long_double_type_node)
2190 code = BUILT_IN_TM_STORE_LDOUBLE;
2191 else if (TYPE_SIZE_UNIT (type) != NULL
2192 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2194 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2196 case 1:
2197 code = BUILT_IN_TM_STORE_1;
2198 break;
2199 case 2:
2200 code = BUILT_IN_TM_STORE_2;
2201 break;
2202 case 4:
2203 code = BUILT_IN_TM_STORE_4;
2204 break;
2205 case 8:
2206 code = BUILT_IN_TM_STORE_8;
2207 break;
2211 if (code == END_BUILTINS)
2213 fn = targetm.vectorize.builtin_tm_store (type);
2214 if (!fn)
2215 return NULL;
2217 else
2218 fn = builtin_decl_explicit (code);
2220 simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2222 if (TREE_CODE (rhs) == CONSTRUCTOR)
2224 /* Handle the easy initialization to zero. */
2225 if (!CONSTRUCTOR_ELTS (rhs))
2226 rhs = build_int_cst (simple_type, 0);
2227 else
2229 /* ...otherwise punt to the caller and probably use
2230 BUILT_IN_TM_MEMMOVE, because we can't wrap a
2231 VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2232 valid gimple. */
2233 return NULL;
2236 else if (!useless_type_conversion_p (simple_type, type))
2238 gimple g;
2239 tree temp;
2241 temp = create_tmp_reg (simple_type);
2242 t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2243 g = gimple_build_assign (temp, t);
2244 gimple_set_location (g, loc);
2245 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2247 rhs = temp;
2250 t = gimplify_addr (gsi, lhs);
2251 gcall = gimple_build_call (fn, 2, t, rhs);
2252 gimple_set_location (gcall, loc);
2253 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2255 return gcall;
2259 /* Expand an assignment statement into transactional builtins. */
2261 static void
2262 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2264 gimple stmt = gsi_stmt (*gsi);
2265 location_t loc = gimple_location (stmt);
2266 tree lhs = gimple_assign_lhs (stmt);
2267 tree rhs = gimple_assign_rhs1 (stmt);
2268 bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2269 bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2270 gimple gcall = NULL;
2272 if (!load_p && !store_p)
2274 /* Add thread private addresses to log if applicable. */
2275 requires_barrier (region->entry_block, lhs, stmt);
2276 gsi_next (gsi);
2277 return;
2280 // Remove original load/store statement.
2281 gsi_remove (gsi, true);
2283 if (load_p && !store_p)
2285 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2286 gcall = build_tm_load (loc, lhs, rhs, gsi);
2288 else if (store_p && !load_p)
2290 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2291 gcall = build_tm_store (loc, lhs, rhs, gsi);
2293 if (!gcall)
2295 tree lhs_addr, rhs_addr, tmp;
2297 if (load_p)
2298 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2299 if (store_p)
2300 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2302 /* ??? Figure out if there's any possible overlap between the LHS
2303 and the RHS and if not, use MEMCPY. */
2305 if (load_p && is_gimple_reg (lhs))
2307 tmp = create_tmp_var (TREE_TYPE (lhs));
2308 lhs_addr = build_fold_addr_expr (tmp);
2310 else
2312 tmp = NULL_TREE;
2313 lhs_addr = gimplify_addr (gsi, lhs);
2315 rhs_addr = gimplify_addr (gsi, rhs);
2316 gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2317 3, lhs_addr, rhs_addr,
2318 TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2319 gimple_set_location (gcall, loc);
2320 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2322 if (tmp)
2324 gcall = gimple_build_assign (lhs, tmp);
2325 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2329 /* Now that we have the load/store in its instrumented form, add
2330 thread private addresses to the log if applicable. */
2331 if (!store_p)
2332 requires_barrier (region->entry_block, lhs, gcall);
2334 // The calls to build_tm_{store,load} above inserted the instrumented
2335 // call into the stream.
2336 // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2340 /* Expand a call statement as appropriate for a transaction. That is,
2341 either verify that the call does not affect the transaction, or
2342 redirect the call to a clone that handles transactions, or change
2343 the transaction state to IRREVOCABLE. Return true if the call is
2344 one of the builtins that end a transaction. */
2346 static bool
2347 expand_call_tm (struct tm_region *region,
2348 gimple_stmt_iterator *gsi)
2350 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2351 tree lhs = gimple_call_lhs (stmt);
2352 tree fn_decl;
2353 struct cgraph_node *node;
2354 bool retval = false;
2356 fn_decl = gimple_call_fndecl (stmt);
2358 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2359 || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2360 transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2361 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2362 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2364 if (is_tm_pure_call (stmt))
2365 return false;
2367 if (fn_decl)
2368 retval = is_tm_ending_fndecl (fn_decl);
2369 if (!retval)
2371 /* Assume all non-const/pure calls write to memory, except
2372 transaction ending builtins. */
2373 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2376 /* For indirect calls, we already generated a call into the runtime. */
2377 if (!fn_decl)
2379 tree fn = gimple_call_fn (stmt);
2381 /* We are guaranteed never to go irrevocable on a safe or pure
2382 call, and the pure call was handled above. */
2383 if (is_tm_safe (fn))
2384 return false;
2385 else
2386 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2388 return false;
2391 node = cgraph_node::get (fn_decl);
2392 /* All calls should have cgraph here. */
2393 if (!node)
2395 /* We can have a nodeless call here if some pass after IPA-tm
2396 added uninstrumented calls. For example, loop distribution
2397 can transform certain loop constructs into __builtin_mem*
2398 calls. In this case, see if we have a suitable TM
2399 replacement and fill in the gaps. */
2400 gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2401 enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2402 gcc_assert (code == BUILT_IN_MEMCPY
2403 || code == BUILT_IN_MEMMOVE
2404 || code == BUILT_IN_MEMSET);
2406 tree repl = find_tm_replacement_function (fn_decl);
2407 if (repl)
2409 gimple_call_set_fndecl (stmt, repl);
2410 update_stmt (stmt);
2411 node = cgraph_node::create (repl);
2412 node->local.tm_may_enter_irr = false;
2413 return expand_call_tm (region, gsi);
2415 gcc_unreachable ();
2417 if (node->local.tm_may_enter_irr)
2418 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2420 if (is_tm_abort (fn_decl))
2422 transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2423 return true;
2426 /* Instrument the store if needed.
2428 If the assignment happens inside the function call (return slot
2429 optimization), there is no instrumentation to be done, since
2430 the callee should have done the right thing. */
2431 if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2432 && !gimple_call_return_slot_opt_p (stmt))
2434 tree tmp = create_tmp_reg (TREE_TYPE (lhs));
2435 location_t loc = gimple_location (stmt);
2436 edge fallthru_edge = NULL;
2437 gassign *assign_stmt;
2439 /* Remember if the call was going to throw. */
2440 if (stmt_can_throw_internal (stmt))
2442 edge_iterator ei;
2443 edge e;
2444 basic_block bb = gimple_bb (stmt);
2446 FOR_EACH_EDGE (e, ei, bb->succs)
2447 if (e->flags & EDGE_FALLTHRU)
2449 fallthru_edge = e;
2450 break;
2454 gimple_call_set_lhs (stmt, tmp);
2455 update_stmt (stmt);
2456 assign_stmt = gimple_build_assign (lhs, tmp);
2457 gimple_set_location (assign_stmt, loc);
2459 /* We cannot throw in the middle of a BB. If the call was going
2460 to throw, place the instrumentation on the fallthru edge, so
2461 the call remains the last statement in the block. */
2462 if (fallthru_edge)
2464 gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (assign_stmt);
2465 gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2466 expand_assign_tm (region, &fallthru_gsi);
2467 gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2468 pending_edge_inserts_p = true;
2470 else
2472 gsi_insert_after (gsi, assign_stmt, GSI_CONTINUE_LINKING);
2473 expand_assign_tm (region, gsi);
2476 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2479 return retval;
2483 /* Expand all statements in BB as appropriate for being inside
2484 a transaction. */
2486 static void
2487 expand_block_tm (struct tm_region *region, basic_block bb)
2489 gimple_stmt_iterator gsi;
2491 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2493 gimple stmt = gsi_stmt (gsi);
2494 switch (gimple_code (stmt))
2496 case GIMPLE_ASSIGN:
2497 /* Only memory reads/writes need to be instrumented. */
2498 if (gimple_assign_single_p (stmt)
2499 && !gimple_clobber_p (stmt))
2501 expand_assign_tm (region, &gsi);
2502 continue;
2504 break;
2506 case GIMPLE_CALL:
2507 if (expand_call_tm (region, &gsi))
2508 return;
2509 break;
2511 case GIMPLE_ASM:
2512 gcc_unreachable ();
2514 default:
2515 break;
2517 if (!gsi_end_p (gsi))
2518 gsi_next (&gsi);
2522 /* Return the list of basic-blocks in REGION.
2524 STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2525 following a TM_IRREVOCABLE call.
2527 INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2528 uninstrumented code path blocks in the list of basic blocks
2529 returned, false otherwise. */
2531 static vec<basic_block>
2532 get_tm_region_blocks (basic_block entry_block,
2533 bitmap exit_blocks,
2534 bitmap irr_blocks,
2535 bitmap all_region_blocks,
2536 bool stop_at_irrevocable_p,
2537 bool include_uninstrumented_p = true)
2539 vec<basic_block> bbs = vNULL;
2540 unsigned i;
2541 edge e;
2542 edge_iterator ei;
2543 bitmap visited_blocks = BITMAP_ALLOC (NULL);
2545 i = 0;
2546 bbs.safe_push (entry_block);
2547 bitmap_set_bit (visited_blocks, entry_block->index);
2551 basic_block bb = bbs[i++];
2553 if (exit_blocks &&
2554 bitmap_bit_p (exit_blocks, bb->index))
2555 continue;
2557 if (stop_at_irrevocable_p
2558 && irr_blocks
2559 && bitmap_bit_p (irr_blocks, bb->index))
2560 continue;
2562 FOR_EACH_EDGE (e, ei, bb->succs)
2563 if ((include_uninstrumented_p
2564 || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2565 && !bitmap_bit_p (visited_blocks, e->dest->index))
2567 bitmap_set_bit (visited_blocks, e->dest->index);
2568 bbs.safe_push (e->dest);
2571 while (i < bbs.length ());
2573 if (all_region_blocks)
2574 bitmap_ior_into (all_region_blocks, visited_blocks);
2576 BITMAP_FREE (visited_blocks);
2577 return bbs;
2580 // Callback data for collect_bb2reg.
2581 struct bb2reg_stuff
2583 vec<tm_region_p> *bb2reg;
2584 bool include_uninstrumented_p;
2587 // Callback for expand_regions, collect innermost region data for each bb.
2588 static void *
2589 collect_bb2reg (struct tm_region *region, void *data)
2591 struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2592 vec<tm_region_p> *bb2reg = stuff->bb2reg;
2593 vec<basic_block> queue;
2594 unsigned int i;
2595 basic_block bb;
2597 queue = get_tm_region_blocks (region->entry_block,
2598 region->exit_blocks,
2599 region->irr_blocks,
2600 NULL,
2601 /*stop_at_irr_p=*/true,
2602 stuff->include_uninstrumented_p);
2604 // We expect expand_region to perform a post-order traversal of the region
2605 // tree. Therefore the last region seen for any bb is the innermost.
2606 FOR_EACH_VEC_ELT (queue, i, bb)
2607 (*bb2reg)[bb->index] = region;
2609 queue.release ();
2610 return NULL;
2613 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2614 // which a basic block belongs. Note that we only consider the instrumented
2615 // code paths for the region; the uninstrumented code paths are ignored if
2616 // INCLUDE_UNINSTRUMENTED_P is false.
2618 // ??? This data is very similar to the bb_regions array that is collected
2619 // during tm_region_init. Or, rather, this data is similar to what could
2620 // be used within tm_region_init. The actual computation in tm_region_init
2621 // begins and ends with bb_regions entirely full of NULL pointers, due to
2622 // the way in which pointers are swapped in and out of the array.
2624 // ??? Our callers expect that blocks are not shared between transactions.
2625 // When the optimizers get too smart, and blocks are shared, then during
2626 // the tm_mark phase we'll add log entries to only one of the two transactions,
2627 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2628 // cycles. The symptom being SSA defs that do not dominate their uses.
2629 // Note that the optimizers were locally correct with their transformation,
2630 // as we have no info within the program that suggests that the blocks cannot
2631 // be shared.
2633 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2634 // only known instance of this block sharing.
2636 static vec<tm_region_p>
2637 get_bb_regions_instrumented (bool traverse_clones,
2638 bool include_uninstrumented_p)
2640 unsigned n = last_basic_block_for_fn (cfun);
2641 struct bb2reg_stuff stuff;
2642 vec<tm_region_p> ret;
2644 ret.create (n);
2645 ret.safe_grow_cleared (n);
2646 stuff.bb2reg = &ret;
2647 stuff.include_uninstrumented_p = include_uninstrumented_p;
2648 expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2650 return ret;
2653 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2654 transaction. */
2656 void
2657 compute_transaction_bits (void)
2659 struct tm_region *region;
2660 vec<basic_block> queue;
2661 unsigned int i;
2662 basic_block bb;
2664 /* ?? Perhaps we need to abstract gate_tm_init further, because we
2665 certainly don't need it to calculate CDI_DOMINATOR info. */
2666 gate_tm_init ();
2668 FOR_EACH_BB_FN (bb, cfun)
2669 bb->flags &= ~BB_IN_TRANSACTION;
2671 for (region = all_tm_regions; region; region = region->next)
2673 queue = get_tm_region_blocks (region->entry_block,
2674 region->exit_blocks,
2675 region->irr_blocks,
2676 NULL,
2677 /*stop_at_irr_p=*/true);
2678 for (i = 0; queue.iterate (i, &bb); ++i)
2679 bb->flags |= BB_IN_TRANSACTION;
2680 queue.release ();
2683 if (all_tm_regions)
2684 bitmap_obstack_release (&tm_obstack);
2687 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2688 call to BUILT_IN_TM_START. */
2690 static void *
2691 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2693 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2694 basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2695 tree tm_state = region->tm_state;
2696 tree tm_state_type = TREE_TYPE (tm_state);
2697 edge abort_edge = NULL;
2698 edge inst_edge = NULL;
2699 edge uninst_edge = NULL;
2700 edge fallthru_edge = NULL;
2702 // Identify the various successors of the transaction start.
2704 edge_iterator i;
2705 edge e;
2706 FOR_EACH_EDGE (e, i, transaction_bb->succs)
2708 if (e->flags & EDGE_TM_ABORT)
2709 abort_edge = e;
2710 else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2711 uninst_edge = e;
2712 else
2713 inst_edge = e;
2714 if (e->flags & EDGE_FALLTHRU)
2715 fallthru_edge = e;
2719 /* ??? There are plenty of bits here we're not computing. */
2721 int subcode = gimple_transaction_subcode (region->get_transaction_stmt ());
2722 int flags = 0;
2723 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2724 flags |= PR_DOESGOIRREVOCABLE;
2725 if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2726 flags |= PR_HASNOIRREVOCABLE;
2727 /* If the transaction does not have an abort in lexical scope and is not
2728 marked as an outer transaction, then it will never abort. */
2729 if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2730 flags |= PR_HASNOABORT;
2731 if ((subcode & GTMA_HAVE_STORE) == 0)
2732 flags |= PR_READONLY;
2733 if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2734 flags |= PR_INSTRUMENTEDCODE;
2735 if (uninst_edge)
2736 flags |= PR_UNINSTRUMENTEDCODE;
2737 if (subcode & GTMA_IS_OUTER)
2738 region->original_transaction_was_outer = true;
2739 tree t = build_int_cst (tm_state_type, flags);
2740 gcall *call = gimple_build_call (tm_start, 1, t);
2741 gimple_call_set_lhs (call, tm_state);
2742 gimple_set_location (call, gimple_location (region->transaction_stmt));
2744 // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2745 gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2746 gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2747 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2748 gsi_remove (&gsi, true);
2749 region->transaction_stmt = call;
2752 // Generate log saves.
2753 if (!tm_log_save_addresses.is_empty ())
2754 tm_log_emit_saves (region->entry_block, transaction_bb);
2756 // In the beginning, we've no tests to perform on transaction restart.
2757 // Note that after this point, transaction_bb becomes the "most recent
2758 // block containing tests for the transaction".
2759 region->restart_block = region->entry_block;
2761 // Generate log restores.
2762 if (!tm_log_save_addresses.is_empty ())
2764 basic_block test_bb = create_empty_bb (transaction_bb);
2765 basic_block code_bb = create_empty_bb (test_bb);
2766 basic_block join_bb = create_empty_bb (code_bb);
2767 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2768 add_bb_to_loop (code_bb, transaction_bb->loop_father);
2769 add_bb_to_loop (join_bb, transaction_bb->loop_father);
2770 if (region->restart_block == region->entry_block)
2771 region->restart_block = test_bb;
2773 tree t1 = create_tmp_reg (tm_state_type);
2774 tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2775 gimple stmt = gimple_build_assign (t1, BIT_AND_EXPR, tm_state, t2);
2776 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2777 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2779 t2 = build_int_cst (tm_state_type, 0);
2780 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2781 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2783 tm_log_emit_restores (region->entry_block, code_bb);
2785 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2786 edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2787 edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2788 redirect_edge_pred (fallthru_edge, join_bb);
2790 join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2791 join_bb->count = test_bb->count = transaction_bb->count;
2793 ei->probability = PROB_ALWAYS;
2794 et->probability = PROB_LIKELY;
2795 ef->probability = PROB_UNLIKELY;
2796 et->count = apply_probability (test_bb->count, et->probability);
2797 ef->count = apply_probability (test_bb->count, ef->probability);
2799 code_bb->count = et->count;
2800 code_bb->frequency = EDGE_FREQUENCY (et);
2802 transaction_bb = join_bb;
2805 // If we have an ABORT edge, create a test to perform the abort.
2806 if (abort_edge)
2808 basic_block test_bb = create_empty_bb (transaction_bb);
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);
2814 tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2815 gimple stmt = gimple_build_assign (t1, BIT_AND_EXPR, tm_state, t2);
2816 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2817 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2819 t2 = build_int_cst (tm_state_type, 0);
2820 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2821 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2823 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2824 test_bb->frequency = transaction_bb->frequency;
2825 test_bb->count = transaction_bb->count;
2826 ei->probability = PROB_ALWAYS;
2828 // Not abort edge. If both are live, chose one at random as we'll
2829 // we'll be fixing that up below.
2830 redirect_edge_pred (fallthru_edge, test_bb);
2831 fallthru_edge->flags = EDGE_FALSE_VALUE;
2832 fallthru_edge->probability = PROB_VERY_LIKELY;
2833 fallthru_edge->count
2834 = apply_probability (test_bb->count, fallthru_edge->probability);
2836 // Abort/over edge.
2837 redirect_edge_pred (abort_edge, test_bb);
2838 abort_edge->flags = EDGE_TRUE_VALUE;
2839 abort_edge->probability = PROB_VERY_UNLIKELY;
2840 abort_edge->count
2841 = apply_probability (test_bb->count, abort_edge->probability);
2843 transaction_bb = test_bb;
2846 // If we have both instrumented and uninstrumented code paths, select one.
2847 if (inst_edge && uninst_edge)
2849 basic_block test_bb = create_empty_bb (transaction_bb);
2850 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2851 if (region->restart_block == region->entry_block)
2852 region->restart_block = test_bb;
2854 tree t1 = create_tmp_reg (tm_state_type);
2855 tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2857 gimple stmt = gimple_build_assign (t1, BIT_AND_EXPR, tm_state, t2);
2858 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2859 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2861 t2 = build_int_cst (tm_state_type, 0);
2862 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2863 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2865 // Create the edge into test_bb first, as we want to copy values
2866 // out of the fallthru edge.
2867 edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2868 e->probability = fallthru_edge->probability;
2869 test_bb->count = e->count = fallthru_edge->count;
2870 test_bb->frequency = EDGE_FREQUENCY (e);
2872 // Now update the edges to the inst/uninist implementations.
2873 // For now assume that the paths are equally likely. When using HTM,
2874 // we'll try the uninst path first and fallback to inst path if htm
2875 // buffers are exceeded. Without HTM we start with the inst path and
2876 // use the uninst path when falling back to serial mode.
2877 redirect_edge_pred (inst_edge, test_bb);
2878 inst_edge->flags = EDGE_FALSE_VALUE;
2879 inst_edge->probability = REG_BR_PROB_BASE / 2;
2880 inst_edge->count
2881 = apply_probability (test_bb->count, inst_edge->probability);
2883 redirect_edge_pred (uninst_edge, test_bb);
2884 uninst_edge->flags = EDGE_TRUE_VALUE;
2885 uninst_edge->probability = REG_BR_PROB_BASE / 2;
2886 uninst_edge->count
2887 = apply_probability (test_bb->count, uninst_edge->probability);
2890 // If we have no previous special cases, and we have PHIs at the beginning
2891 // of the atomic region, this means we have a loop at the beginning of the
2892 // atomic region that shares the first block. This can cause problems with
2893 // the transaction restart abnormal edges to be added in the tm_edges pass.
2894 // Solve this by adding a new empty block to receive the abnormal edges.
2895 if (region->restart_block == region->entry_block
2896 && phi_nodes (region->entry_block))
2898 basic_block empty_bb = create_empty_bb (transaction_bb);
2899 region->restart_block = empty_bb;
2900 add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2902 redirect_edge_pred (fallthru_edge, empty_bb);
2903 make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2906 return NULL;
2909 /* Generate the temporary to be used for the return value of
2910 BUILT_IN_TM_START. */
2912 static void *
2913 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2915 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2916 region->tm_state =
2917 create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2919 // Reset the subcode, post optimizations. We'll fill this in
2920 // again as we process blocks.
2921 if (region->exit_blocks)
2923 gtransaction *transaction_stmt = region->get_transaction_stmt ();
2924 unsigned int subcode = gimple_transaction_subcode (transaction_stmt);
2926 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2927 subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2928 | GTMA_MAY_ENTER_IRREVOCABLE
2929 | GTMA_HAS_NO_INSTRUMENTATION);
2930 else
2931 subcode &= GTMA_DECLARATION_MASK;
2932 gimple_transaction_set_subcode (transaction_stmt, subcode);
2935 return NULL;
2938 // Propagate flags from inner transactions outwards.
2939 static void
2940 propagate_tm_flags_out (struct tm_region *region)
2942 if (region == NULL)
2943 return;
2944 propagate_tm_flags_out (region->inner);
2946 if (region->outer && region->outer->transaction_stmt)
2948 unsigned s
2949 = gimple_transaction_subcode (region->get_transaction_stmt ());
2950 s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2951 | GTMA_MAY_ENTER_IRREVOCABLE);
2952 s |= gimple_transaction_subcode (region->outer->get_transaction_stmt ());
2953 gimple_transaction_set_subcode (region->outer->get_transaction_stmt (),
2957 propagate_tm_flags_out (region->next);
2960 /* Entry point to the MARK phase of TM expansion. Here we replace
2961 transactional memory statements with calls to builtins, and function
2962 calls with their transactional clones (if available). But we don't
2963 yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges. */
2965 static unsigned int
2966 execute_tm_mark (void)
2968 pending_edge_inserts_p = false;
2970 expand_regions (all_tm_regions, generate_tm_state, NULL,
2971 /*traverse_clones=*/true);
2973 tm_log_init ();
2975 vec<tm_region_p> bb_regions
2976 = get_bb_regions_instrumented (/*traverse_clones=*/true,
2977 /*include_uninstrumented_p=*/false);
2978 struct tm_region *r;
2979 unsigned i;
2981 // Expand memory operations into calls into the runtime.
2982 // This collects log entries as well.
2983 FOR_EACH_VEC_ELT (bb_regions, i, r)
2985 if (r != NULL)
2987 if (r->transaction_stmt)
2989 unsigned sub
2990 = gimple_transaction_subcode (r->get_transaction_stmt ());
2992 /* If we're sure to go irrevocable, there won't be
2993 anything to expand, since the run-time will go
2994 irrevocable right away. */
2995 if (sub & GTMA_DOES_GO_IRREVOCABLE
2996 && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2997 continue;
2999 expand_block_tm (r, BASIC_BLOCK_FOR_FN (cfun, i));
3003 bb_regions.release ();
3005 // Propagate flags from inner transactions outwards.
3006 propagate_tm_flags_out (all_tm_regions);
3008 // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
3009 expand_regions (all_tm_regions, expand_transaction, NULL,
3010 /*traverse_clones=*/false);
3012 tm_log_emit ();
3013 tm_log_delete ();
3015 if (pending_edge_inserts_p)
3016 gsi_commit_edge_inserts ();
3017 free_dominance_info (CDI_DOMINATORS);
3018 return 0;
3021 static const pass_data pass_data_tm_mark =
3023 GIMPLE_PASS, /* type */
3024 "tmmark", /* name */
3025 OPTGROUP_NONE, /* optinfo_flags */
3026 TV_TRANS_MEM, /* tv_id */
3027 ( PROP_ssa | PROP_cfg ), /* properties_required */
3028 0, /* properties_provided */
3029 0, /* properties_destroyed */
3030 0, /* todo_flags_start */
3031 TODO_update_ssa, /* todo_flags_finish */
3034 class pass_tm_mark GCC_FINAL : public gimple_opt_pass
3036 public:
3037 pass_tm_mark (gcc::context *ctxt)
3038 : gimple_opt_pass (pass_data_tm_mark, ctxt)
3041 /* opt_pass methods: */
3042 virtual unsigned int execute (function *) { return execute_tm_mark (); }
3044 }; // class pass_tm_mark
3046 gimple_opt_pass *
3047 make_pass_tm_mark (gcc::context *ctxt)
3049 return new pass_tm_mark (ctxt);
3053 /* Create an abnormal edge from STMT at iter, splitting the block
3054 as necessary. Adjust *PNEXT as needed for the split block. */
3056 static inline void
3057 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3058 gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3060 basic_block bb = gimple_bb (stmt);
3061 if (!gsi_one_before_end_p (iter))
3063 edge e = split_block (bb, stmt);
3064 *pnext = gsi_start_bb (e->dest);
3066 make_edge (bb, dest_bb, EDGE_ABNORMAL);
3068 // Record the need for the edge for the benefit of the rtl passes.
3069 if (cfun->gimple_df->tm_restart == NULL)
3070 cfun->gimple_df->tm_restart
3071 = hash_table<tm_restart_hasher>::create_ggc (31);
3073 struct tm_restart_node dummy;
3074 dummy.stmt = stmt;
3075 dummy.label_or_list = gimple_block_label (dest_bb);
3077 tm_restart_node **slot = cfun->gimple_df->tm_restart->find_slot (&dummy,
3078 INSERT);
3079 struct tm_restart_node *n = *slot;
3080 if (n == NULL)
3082 n = ggc_alloc<tm_restart_node> ();
3083 *n = dummy;
3085 else
3087 tree old = n->label_or_list;
3088 if (TREE_CODE (old) == LABEL_DECL)
3089 old = tree_cons (NULL, old, NULL);
3090 n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3094 /* Split block BB as necessary for every builtin function we added, and
3095 wire up the abnormal back edges implied by the transaction restart. */
3097 static void
3098 expand_block_edges (struct tm_region *const region, basic_block bb)
3100 gimple_stmt_iterator gsi, next_gsi;
3102 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3104 gimple stmt = gsi_stmt (gsi);
3105 gcall *call_stmt;
3107 next_gsi = gsi;
3108 gsi_next (&next_gsi);
3110 // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3111 call_stmt = dyn_cast <gcall *> (stmt);
3112 if ((!call_stmt)
3113 || (gimple_call_flags (call_stmt) & ECF_TM_BUILTIN) == 0)
3114 continue;
3116 if (DECL_FUNCTION_CODE (gimple_call_fndecl (call_stmt))
3117 == BUILT_IN_TM_ABORT)
3119 // If we have a ``_transaction_cancel [[outer]]'', there is only
3120 // one abnormal edge: to the transaction marked OUTER.
3121 // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3122 // constant argument, which we can examine here. Users invoking
3123 // TM_ABORT directly get what they deserve.
3124 tree arg = gimple_call_arg (call_stmt, 0);
3125 if (TREE_CODE (arg) == INTEGER_CST
3126 && (TREE_INT_CST_LOW (arg) & AR_OUTERABORT) != 0
3127 && !decl_is_tm_clone (current_function_decl))
3129 // Find the GTMA_IS_OUTER transaction.
3130 for (struct tm_region *o = region; o; o = o->outer)
3131 if (o->original_transaction_was_outer)
3133 split_bb_make_tm_edge (call_stmt, o->restart_block,
3134 gsi, &next_gsi);
3135 break;
3138 // Otherwise, the front-end should have semantically checked
3139 // outer aborts, but in either case the target region is not
3140 // within this function.
3141 continue;
3144 // Non-outer, TM aborts have an abnormal edge to the inner-most
3145 // transaction, the one being aborted;
3146 split_bb_make_tm_edge (call_stmt, region->restart_block, gsi,
3147 &next_gsi);
3150 // All TM builtins have an abnormal edge to the outer-most transaction.
3151 // We never restart inner transactions. For tm clones, we know a-priori
3152 // that the outer-most transaction is outside the function.
3153 if (decl_is_tm_clone (current_function_decl))
3154 continue;
3156 if (cfun->gimple_df->tm_restart == NULL)
3157 cfun->gimple_df->tm_restart
3158 = hash_table<tm_restart_hasher>::create_ggc (31);
3160 // All TM builtins have an abnormal edge to the outer-most transaction.
3161 // We never restart inner transactions.
3162 for (struct tm_region *o = region; o; o = o->outer)
3163 if (!o->outer)
3165 split_bb_make_tm_edge (call_stmt, o->restart_block, gsi, &next_gsi);
3166 break;
3169 // Delete any tail-call annotation that may have been added.
3170 // The tail-call pass may have mis-identified the commit as being
3171 // a candidate because we had not yet added this restart edge.
3172 gimple_call_set_tail (call_stmt, false);
3176 /* Entry point to the final expansion of transactional nodes. */
3178 static const pass_data pass_data_tm_edges =
3180 GIMPLE_PASS, /* type */
3181 "tmedge", /* name */
3182 OPTGROUP_NONE, /* optinfo_flags */
3183 TV_TRANS_MEM, /* tv_id */
3184 ( PROP_ssa | PROP_cfg ), /* properties_required */
3185 0, /* properties_provided */
3186 0, /* properties_destroyed */
3187 0, /* todo_flags_start */
3188 TODO_update_ssa, /* todo_flags_finish */
3191 class pass_tm_edges GCC_FINAL : public gimple_opt_pass
3193 public:
3194 pass_tm_edges (gcc::context *ctxt)
3195 : gimple_opt_pass (pass_data_tm_edges, ctxt)
3198 /* opt_pass methods: */
3199 virtual unsigned int execute (function *);
3201 }; // class pass_tm_edges
3203 unsigned int
3204 pass_tm_edges::execute (function *fun)
3206 vec<tm_region_p> bb_regions
3207 = get_bb_regions_instrumented (/*traverse_clones=*/false,
3208 /*include_uninstrumented_p=*/true);
3209 struct tm_region *r;
3210 unsigned i;
3212 FOR_EACH_VEC_ELT (bb_regions, i, r)
3213 if (r != NULL)
3214 expand_block_edges (r, BASIC_BLOCK_FOR_FN (fun, i));
3216 bb_regions.release ();
3218 /* We've got to release the dominance info now, to indicate that it
3219 must be rebuilt completely. Otherwise we'll crash trying to update
3220 the SSA web in the TODO section following this pass. */
3221 free_dominance_info (CDI_DOMINATORS);
3222 bitmap_obstack_release (&tm_obstack);
3223 all_tm_regions = NULL;
3225 return 0;
3228 gimple_opt_pass *
3229 make_pass_tm_edges (gcc::context *ctxt)
3231 return new pass_tm_edges (ctxt);
3234 /* Helper function for expand_regions. Expand REGION and recurse to
3235 the inner region. Call CALLBACK on each region. CALLBACK returns
3236 NULL to continue the traversal, otherwise a non-null value which
3237 this function will return as well. TRAVERSE_CLONES is true if we
3238 should traverse transactional clones. */
3240 static void *
3241 expand_regions_1 (struct tm_region *region,
3242 void *(*callback)(struct tm_region *, void *),
3243 void *data,
3244 bool traverse_clones)
3246 void *retval = NULL;
3247 if (region->exit_blocks
3248 || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3250 retval = callback (region, data);
3251 if (retval)
3252 return retval;
3254 if (region->inner)
3256 retval = expand_regions (region->inner, callback, data, traverse_clones);
3257 if (retval)
3258 return retval;
3260 return retval;
3263 /* Traverse the regions enclosed and including REGION. Execute
3264 CALLBACK for each region, passing DATA. CALLBACK returns NULL to
3265 continue the traversal, otherwise a non-null value which this
3266 function will return as well. TRAVERSE_CLONES is true if we should
3267 traverse transactional clones. */
3269 static void *
3270 expand_regions (struct tm_region *region,
3271 void *(*callback)(struct tm_region *, void *),
3272 void *data,
3273 bool traverse_clones)
3275 void *retval = NULL;
3276 while (region)
3278 retval = expand_regions_1 (region, callback, data, traverse_clones);
3279 if (retval)
3280 return retval;
3281 region = region->next;
3283 return retval;
3287 /* A unique TM memory operation. */
3288 typedef struct tm_memop
3290 /* Unique ID that all memory operations to the same location have. */
3291 unsigned int value_id;
3292 /* Address of load/store. */
3293 tree addr;
3294 } *tm_memop_t;
3296 /* TM memory operation hashtable helpers. */
3298 struct tm_memop_hasher : free_ptr_hash <tm_memop>
3300 static inline hashval_t hash (const tm_memop *);
3301 static inline bool equal (const tm_memop *, const tm_memop *);
3304 /* Htab support. Return a hash value for a `tm_memop'. */
3305 inline hashval_t
3306 tm_memop_hasher::hash (const tm_memop *mem)
3308 tree addr = mem->addr;
3309 /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3310 actually done with operand_equal_p (see tm_memop_eq). */
3311 if (TREE_CODE (addr) == ADDR_EXPR)
3312 addr = TREE_OPERAND (addr, 0);
3313 return iterative_hash_expr (addr, 0);
3316 /* Htab support. Return true if two tm_memop's are the same. */
3317 inline bool
3318 tm_memop_hasher::equal (const tm_memop *mem1, const tm_memop *mem2)
3320 return operand_equal_p (mem1->addr, mem2->addr, 0);
3323 /* Sets for solving data flow equations in the memory optimization pass. */
3324 struct tm_memopt_bitmaps
3326 /* Stores available to this BB upon entry. Basically, stores that
3327 dominate this BB. */
3328 bitmap store_avail_in;
3329 /* Stores available at the end of this BB. */
3330 bitmap store_avail_out;
3331 bitmap store_antic_in;
3332 bitmap store_antic_out;
3333 /* Reads available to this BB upon entry. Basically, reads that
3334 dominate this BB. */
3335 bitmap read_avail_in;
3336 /* Reads available at the end of this BB. */
3337 bitmap read_avail_out;
3338 /* Reads performed in this BB. */
3339 bitmap read_local;
3340 /* Writes performed in this BB. */
3341 bitmap store_local;
3343 /* Temporary storage for pass. */
3344 /* Is the current BB in the worklist? */
3345 bool avail_in_worklist_p;
3346 /* Have we visited this BB? */
3347 bool visited_p;
3350 static bitmap_obstack tm_memopt_obstack;
3352 /* Unique counter for TM loads and stores. Loads and stores of the
3353 same address get the same ID. */
3354 static unsigned int tm_memopt_value_id;
3355 static hash_table<tm_memop_hasher> *tm_memopt_value_numbers;
3357 #define STORE_AVAIL_IN(BB) \
3358 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3359 #define STORE_AVAIL_OUT(BB) \
3360 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3361 #define STORE_ANTIC_IN(BB) \
3362 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3363 #define STORE_ANTIC_OUT(BB) \
3364 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3365 #define READ_AVAIL_IN(BB) \
3366 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3367 #define READ_AVAIL_OUT(BB) \
3368 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3369 #define READ_LOCAL(BB) \
3370 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3371 #define STORE_LOCAL(BB) \
3372 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3373 #define AVAIL_IN_WORKLIST_P(BB) \
3374 ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3375 #define BB_VISITED_P(BB) \
3376 ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3378 /* Given a TM load/store in STMT, return the value number for the address
3379 it accesses. */
3381 static unsigned int
3382 tm_memopt_value_number (gimple stmt, enum insert_option op)
3384 struct tm_memop tmpmem, *mem;
3385 tm_memop **slot;
3387 gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3388 tmpmem.addr = gimple_call_arg (stmt, 0);
3389 slot = tm_memopt_value_numbers->find_slot (&tmpmem, op);
3390 if (*slot)
3391 mem = *slot;
3392 else if (op == INSERT)
3394 mem = XNEW (struct tm_memop);
3395 *slot = mem;
3396 mem->value_id = tm_memopt_value_id++;
3397 mem->addr = tmpmem.addr;
3399 else
3400 gcc_unreachable ();
3401 return mem->value_id;
3404 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL. */
3406 static void
3407 tm_memopt_accumulate_memops (basic_block bb)
3409 gimple_stmt_iterator gsi;
3411 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3413 gimple stmt = gsi_stmt (gsi);
3414 bitmap bits;
3415 unsigned int loc;
3417 if (is_tm_store (stmt))
3418 bits = STORE_LOCAL (bb);
3419 else if (is_tm_load (stmt))
3420 bits = READ_LOCAL (bb);
3421 else
3422 continue;
3424 loc = tm_memopt_value_number (stmt, INSERT);
3425 bitmap_set_bit (bits, loc);
3426 if (dump_file)
3428 fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3429 is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3430 gimple_bb (stmt)->index);
3431 print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3432 fprintf (dump_file, "\n");
3437 /* Prettily dump one of the memopt sets. BITS is the bitmap to dump. */
3439 static void
3440 dump_tm_memopt_set (const char *set_name, bitmap bits)
3442 unsigned i;
3443 bitmap_iterator bi;
3444 const char *comma = "";
3446 fprintf (dump_file, "TM memopt: %s: [", set_name);
3447 EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3449 hash_table<tm_memop_hasher>::iterator hi;
3450 struct tm_memop *mem = NULL;
3452 /* Yeah, yeah, yeah. Whatever. This is just for debugging. */
3453 FOR_EACH_HASH_TABLE_ELEMENT (*tm_memopt_value_numbers, mem, tm_memop_t, hi)
3454 if (mem->value_id == i)
3455 break;
3456 gcc_assert (mem->value_id == i);
3457 fprintf (dump_file, "%s", comma);
3458 comma = ", ";
3459 print_generic_expr (dump_file, mem->addr, 0);
3461 fprintf (dump_file, "]\n");
3464 /* Prettily dump all of the memopt sets in BLOCKS. */
3466 static void
3467 dump_tm_memopt_sets (vec<basic_block> blocks)
3469 size_t i;
3470 basic_block bb;
3472 for (i = 0; blocks.iterate (i, &bb); ++i)
3474 fprintf (dump_file, "------------BB %d---------\n", bb->index);
3475 dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3476 dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3477 dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3478 dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3479 dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3480 dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3484 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB. */
3486 static void
3487 tm_memopt_compute_avin (basic_block bb)
3489 edge e;
3490 unsigned ix;
3492 /* Seed with the AVOUT of any predecessor. */
3493 for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3495 e = EDGE_PRED (bb, ix);
3496 /* Make sure we have already visited this BB, and is thus
3497 initialized.
3499 If e->src->aux is NULL, this predecessor is actually on an
3500 enclosing transaction. We only care about the current
3501 transaction, so ignore it. */
3502 if (e->src->aux && BB_VISITED_P (e->src))
3504 bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3505 bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3506 break;
3510 for (; ix < EDGE_COUNT (bb->preds); ix++)
3512 e = EDGE_PRED (bb, ix);
3513 if (e->src->aux && BB_VISITED_P (e->src))
3515 bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3516 bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3520 BB_VISITED_P (bb) = true;
3523 /* Compute the STORE_ANTIC_IN for the basic block BB. */
3525 static void
3526 tm_memopt_compute_antin (basic_block bb)
3528 edge e;
3529 unsigned ix;
3531 /* Seed with the ANTIC_OUT of any successor. */
3532 for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3534 e = EDGE_SUCC (bb, ix);
3535 /* Make sure we have already visited this BB, and is thus
3536 initialized. */
3537 if (BB_VISITED_P (e->dest))
3539 bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3540 break;
3544 for (; ix < EDGE_COUNT (bb->succs); ix++)
3546 e = EDGE_SUCC (bb, ix);
3547 if (BB_VISITED_P (e->dest))
3548 bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3551 BB_VISITED_P (bb) = true;
3554 /* Compute the AVAIL sets for every basic block in BLOCKS.
3556 We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3558 AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3559 AVAIL_IN[bb] = intersect (AVAIL_OUT[predecessors])
3561 This is basically what we do in lcm's compute_available(), but here
3562 we calculate two sets of sets (one for STOREs and one for READs),
3563 and we work on a region instead of the entire CFG.
3565 REGION is the TM region.
3566 BLOCKS are the basic blocks in the region. */
3568 static void
3569 tm_memopt_compute_available (struct tm_region *region,
3570 vec<basic_block> blocks)
3572 edge e;
3573 basic_block *worklist, *qin, *qout, *qend, bb;
3574 unsigned int qlen, i;
3575 edge_iterator ei;
3576 bool changed;
3578 /* Allocate a worklist array/queue. Entries are only added to the
3579 list if they were not already on the list. So the size is
3580 bounded by the number of basic blocks in the region. */
3581 qlen = blocks.length () - 1;
3582 qin = qout = worklist =
3583 XNEWVEC (basic_block, qlen);
3585 /* Put every block in the region on the worklist. */
3586 for (i = 0; blocks.iterate (i, &bb); ++i)
3588 /* Seed AVAIL_OUT with the LOCAL set. */
3589 bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3590 bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3592 AVAIL_IN_WORKLIST_P (bb) = true;
3593 /* No need to insert the entry block, since it has an AVIN of
3594 null, and an AVOUT that has already been seeded in. */
3595 if (bb != region->entry_block)
3596 *qin++ = bb;
3599 /* The entry block has been initialized with the local sets. */
3600 BB_VISITED_P (region->entry_block) = true;
3602 qin = worklist;
3603 qend = &worklist[qlen];
3605 /* Iterate until the worklist is empty. */
3606 while (qlen)
3608 /* Take the first entry off the worklist. */
3609 bb = *qout++;
3610 qlen--;
3612 if (qout >= qend)
3613 qout = worklist;
3615 /* This block can be added to the worklist again if necessary. */
3616 AVAIL_IN_WORKLIST_P (bb) = false;
3617 tm_memopt_compute_avin (bb);
3619 /* Note: We do not add the LOCAL sets here because we already
3620 seeded the AVAIL_OUT sets with them. */
3621 changed = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3622 changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3623 if (changed
3624 && (region->exit_blocks == NULL
3625 || !bitmap_bit_p (region->exit_blocks, bb->index)))
3626 /* If the out state of this block changed, then we need to add
3627 its successors to the worklist if they are not already in. */
3628 FOR_EACH_EDGE (e, ei, bb->succs)
3629 if (!AVAIL_IN_WORKLIST_P (e->dest)
3630 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
3632 *qin++ = e->dest;
3633 AVAIL_IN_WORKLIST_P (e->dest) = true;
3634 qlen++;
3636 if (qin >= qend)
3637 qin = worklist;
3641 free (worklist);
3643 if (dump_file)
3644 dump_tm_memopt_sets (blocks);
3647 /* Compute ANTIC sets for every basic block in BLOCKS.
3649 We compute STORE_ANTIC_OUT as follows:
3651 STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3652 STORE_ANTIC_IN[bb] = intersect(STORE_ANTIC_OUT[successors])
3654 REGION is the TM region.
3655 BLOCKS are the basic blocks in the region. */
3657 static void
3658 tm_memopt_compute_antic (struct tm_region *region,
3659 vec<basic_block> blocks)
3661 edge e;
3662 basic_block *worklist, *qin, *qout, *qend, bb;
3663 unsigned int qlen;
3664 int i;
3665 edge_iterator ei;
3667 /* Allocate a worklist array/queue. Entries are only added to the
3668 list if they were not already on the list. So the size is
3669 bounded by the number of basic blocks in the region. */
3670 qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3672 for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3674 bb = blocks[i];
3676 /* Seed ANTIC_OUT with the LOCAL set. */
3677 bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3679 /* Put every block in the region on the worklist. */
3680 AVAIL_IN_WORKLIST_P (bb) = true;
3681 /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3682 and their ANTIC_OUT has already been seeded in. */
3683 if (region->exit_blocks
3684 && !bitmap_bit_p (region->exit_blocks, bb->index))
3686 qlen++;
3687 *qin++ = bb;
3691 /* The exit blocks have been initialized with the local sets. */
3692 if (region->exit_blocks)
3694 unsigned int i;
3695 bitmap_iterator bi;
3696 EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3697 BB_VISITED_P (BASIC_BLOCK_FOR_FN (cfun, i)) = true;
3700 qin = worklist;
3701 qend = &worklist[qlen];
3703 /* Iterate until the worklist is empty. */
3704 while (qlen)
3706 /* Take the first entry off the worklist. */
3707 bb = *qout++;
3708 qlen--;
3710 if (qout >= qend)
3711 qout = worklist;
3713 /* This block can be added to the worklist again if necessary. */
3714 AVAIL_IN_WORKLIST_P (bb) = false;
3715 tm_memopt_compute_antin (bb);
3717 /* Note: We do not add the LOCAL sets here because we already
3718 seeded the ANTIC_OUT sets with them. */
3719 if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3720 && bb != region->entry_block)
3721 /* If the out state of this block changed, then we need to add
3722 its predecessors to the worklist if they are not already in. */
3723 FOR_EACH_EDGE (e, ei, bb->preds)
3724 if (!AVAIL_IN_WORKLIST_P (e->src))
3726 *qin++ = e->src;
3727 AVAIL_IN_WORKLIST_P (e->src) = true;
3728 qlen++;
3730 if (qin >= qend)
3731 qin = worklist;
3735 free (worklist);
3737 if (dump_file)
3738 dump_tm_memopt_sets (blocks);
3741 /* Offsets of load variants from TM_LOAD. For example,
3742 BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3743 See gtm-builtins.def. */
3744 #define TRANSFORM_RAR 1
3745 #define TRANSFORM_RAW 2
3746 #define TRANSFORM_RFW 3
3747 /* Offsets of store variants from TM_STORE. */
3748 #define TRANSFORM_WAR 1
3749 #define TRANSFORM_WAW 2
3751 /* Inform about a load/store optimization. */
3753 static void
3754 dump_tm_memopt_transform (gimple stmt)
3756 if (dump_file)
3758 fprintf (dump_file, "TM memopt: transforming: ");
3759 print_gimple_stmt (dump_file, stmt, 0, 0);
3760 fprintf (dump_file, "\n");
3764 /* Perform a read/write optimization. Replaces the TM builtin in STMT
3765 by a builtin that is OFFSET entries down in the builtins table in
3766 gtm-builtins.def. */
3768 static void
3769 tm_memopt_transform_stmt (unsigned int offset,
3770 gcall *stmt,
3771 gimple_stmt_iterator *gsi)
3773 tree fn = gimple_call_fn (stmt);
3774 gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3775 TREE_OPERAND (fn, 0)
3776 = builtin_decl_explicit ((enum built_in_function)
3777 (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3778 + offset));
3779 gimple_call_set_fn (stmt, fn);
3780 gsi_replace (gsi, stmt, true);
3781 dump_tm_memopt_transform (stmt);
3784 /* Perform the actual TM memory optimization transformations in the
3785 basic blocks in BLOCKS. */
3787 static void
3788 tm_memopt_transform_blocks (vec<basic_block> blocks)
3790 size_t i;
3791 basic_block bb;
3792 gimple_stmt_iterator gsi;
3794 for (i = 0; blocks.iterate (i, &bb); ++i)
3796 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3798 gimple stmt = gsi_stmt (gsi);
3799 bitmap read_avail = READ_AVAIL_IN (bb);
3800 bitmap store_avail = STORE_AVAIL_IN (bb);
3801 bitmap store_antic = STORE_ANTIC_OUT (bb);
3802 unsigned int loc;
3804 if (is_tm_simple_load (stmt))
3806 gcall *call_stmt = as_a <gcall *> (stmt);
3807 loc = tm_memopt_value_number (stmt, NO_INSERT);
3808 if (store_avail && bitmap_bit_p (store_avail, loc))
3809 tm_memopt_transform_stmt (TRANSFORM_RAW, call_stmt, &gsi);
3810 else if (store_antic && bitmap_bit_p (store_antic, loc))
3812 tm_memopt_transform_stmt (TRANSFORM_RFW, call_stmt, &gsi);
3813 bitmap_set_bit (store_avail, loc);
3815 else if (read_avail && bitmap_bit_p (read_avail, loc))
3816 tm_memopt_transform_stmt (TRANSFORM_RAR, call_stmt, &gsi);
3817 else
3818 bitmap_set_bit (read_avail, loc);
3820 else if (is_tm_simple_store (stmt))
3822 gcall *call_stmt = as_a <gcall *> (stmt);
3823 loc = tm_memopt_value_number (stmt, NO_INSERT);
3824 if (store_avail && bitmap_bit_p (store_avail, loc))
3825 tm_memopt_transform_stmt (TRANSFORM_WAW, call_stmt, &gsi);
3826 else
3828 if (read_avail && bitmap_bit_p (read_avail, loc))
3829 tm_memopt_transform_stmt (TRANSFORM_WAR, call_stmt, &gsi);
3830 bitmap_set_bit (store_avail, loc);
3837 /* Return a new set of bitmaps for a BB. */
3839 static struct tm_memopt_bitmaps *
3840 tm_memopt_init_sets (void)
3842 struct tm_memopt_bitmaps *b
3843 = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3844 b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3845 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3846 b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3847 b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3848 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3849 b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3850 b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3851 b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3852 b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3853 return b;
3856 /* Free sets computed for each BB. */
3858 static void
3859 tm_memopt_free_sets (vec<basic_block> blocks)
3861 size_t i;
3862 basic_block bb;
3864 for (i = 0; blocks.iterate (i, &bb); ++i)
3865 bb->aux = NULL;
3868 /* Clear the visited bit for every basic block in BLOCKS. */
3870 static void
3871 tm_memopt_clear_visited (vec<basic_block> blocks)
3873 size_t i;
3874 basic_block bb;
3876 for (i = 0; blocks.iterate (i, &bb); ++i)
3877 BB_VISITED_P (bb) = false;
3880 /* Replace TM load/stores with hints for the runtime. We handle
3881 things like read-after-write, write-after-read, read-after-read,
3882 read-for-write, etc. */
3884 static unsigned int
3885 execute_tm_memopt (void)
3887 struct tm_region *region;
3888 vec<basic_block> bbs;
3890 tm_memopt_value_id = 0;
3891 tm_memopt_value_numbers = new hash_table<tm_memop_hasher> (10);
3893 for (region = all_tm_regions; region; region = region->next)
3895 /* All the TM stores/loads in the current region. */
3896 size_t i;
3897 basic_block bb;
3899 bitmap_obstack_initialize (&tm_memopt_obstack);
3901 /* Save all BBs for the current region. */
3902 bbs = get_tm_region_blocks (region->entry_block,
3903 region->exit_blocks,
3904 region->irr_blocks,
3905 NULL,
3906 false);
3908 /* Collect all the memory operations. */
3909 for (i = 0; bbs.iterate (i, &bb); ++i)
3911 bb->aux = tm_memopt_init_sets ();
3912 tm_memopt_accumulate_memops (bb);
3915 /* Solve data flow equations and transform each block accordingly. */
3916 tm_memopt_clear_visited (bbs);
3917 tm_memopt_compute_available (region, bbs);
3918 tm_memopt_clear_visited (bbs);
3919 tm_memopt_compute_antic (region, bbs);
3920 tm_memopt_transform_blocks (bbs);
3922 tm_memopt_free_sets (bbs);
3923 bbs.release ();
3924 bitmap_obstack_release (&tm_memopt_obstack);
3925 tm_memopt_value_numbers->empty ();
3928 delete tm_memopt_value_numbers;
3929 tm_memopt_value_numbers = NULL;
3930 return 0;
3933 static const pass_data pass_data_tm_memopt =
3935 GIMPLE_PASS, /* type */
3936 "tmmemopt", /* name */
3937 OPTGROUP_NONE, /* optinfo_flags */
3938 TV_TRANS_MEM, /* tv_id */
3939 ( PROP_ssa | PROP_cfg ), /* properties_required */
3940 0, /* properties_provided */
3941 0, /* properties_destroyed */
3942 0, /* todo_flags_start */
3943 0, /* todo_flags_finish */
3946 class pass_tm_memopt GCC_FINAL : public gimple_opt_pass
3948 public:
3949 pass_tm_memopt (gcc::context *ctxt)
3950 : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3953 /* opt_pass methods: */
3954 virtual bool gate (function *) { return flag_tm && optimize > 0; }
3955 virtual unsigned int execute (function *) { return execute_tm_memopt (); }
3957 }; // class pass_tm_memopt
3959 gimple_opt_pass *
3960 make_pass_tm_memopt (gcc::context *ctxt)
3962 return new pass_tm_memopt (ctxt);
3966 /* Interprocedual analysis for the creation of transactional clones.
3967 The aim of this pass is to find which functions are referenced in
3968 a non-irrevocable transaction context, and for those over which
3969 we have control (or user directive), create a version of the
3970 function which uses only the transactional interface to reference
3971 protected memories. This analysis proceeds in several steps:
3973 (1) Collect the set of all possible transactional clones:
3975 (a) For all local public functions marked tm_callable, push
3976 it onto the tm_callee queue.
3978 (b) For all local functions, scan for calls in transaction blocks.
3979 Push the caller and callee onto the tm_caller and tm_callee
3980 queues. Count the number of callers for each callee.
3982 (c) For each local function on the callee list, assume we will
3983 create a transactional clone. Push *all* calls onto the
3984 callee queues; count the number of clone callers separately
3985 to the number of original callers.
3987 (2) Propagate irrevocable status up the dominator tree:
3989 (a) Any external function on the callee list that is not marked
3990 tm_callable is irrevocable. Push all callers of such onto
3991 a worklist.
3993 (b) For each function on the worklist, mark each block that
3994 contains an irrevocable call. Use the AND operator to
3995 propagate that mark up the dominator tree.
3997 (c) If we reach the entry block for a possible transactional
3998 clone, then the transactional clone is irrevocable, and
3999 we should not create the clone after all. Push all
4000 callers onto the worklist.
4002 (d) Place tm_irrevocable calls at the beginning of the relevant
4003 blocks. Special case here is the entry block for the entire
4004 transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
4005 the library to begin the region in serial mode. Decrement
4006 the call count for all callees in the irrevocable region.
4008 (3) Create the transactional clones:
4010 Any tm_callee that still has a non-zero call count is cloned.
4013 /* This structure is stored in the AUX field of each cgraph_node. */
4014 struct tm_ipa_cg_data
4016 /* The clone of the function that got created. */
4017 struct cgraph_node *clone;
4019 /* The tm regions in the normal function. */
4020 struct tm_region *all_tm_regions;
4022 /* The blocks of the normal/clone functions that contain irrevocable
4023 calls, or blocks that are post-dominated by irrevocable calls. */
4024 bitmap irrevocable_blocks_normal;
4025 bitmap irrevocable_blocks_clone;
4027 /* The blocks of the normal function that are involved in transactions. */
4028 bitmap transaction_blocks_normal;
4030 /* The number of callers to the transactional clone of this function
4031 from normal and transactional clones respectively. */
4032 unsigned tm_callers_normal;
4033 unsigned tm_callers_clone;
4035 /* True if all calls to this function's transactional clone
4036 are irrevocable. Also automatically true if the function
4037 has no transactional clone. */
4038 bool is_irrevocable;
4040 /* Flags indicating the presence of this function in various queues. */
4041 bool in_callee_queue;
4042 bool in_worklist;
4044 /* Flags indicating the kind of scan desired while in the worklist. */
4045 bool want_irr_scan_normal;
4048 typedef vec<cgraph_node *> cgraph_node_queue;
4050 /* Return the ipa data associated with NODE, allocating zeroed memory
4051 if necessary. TRAVERSE_ALIASES is true if we must traverse aliases
4052 and set *NODE accordingly. */
4054 static struct tm_ipa_cg_data *
4055 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4057 struct tm_ipa_cg_data *d;
4059 if (traverse_aliases && (*node)->alias)
4060 *node = (*node)->get_alias_target ();
4062 d = (struct tm_ipa_cg_data *) (*node)->aux;
4064 if (d == NULL)
4066 d = (struct tm_ipa_cg_data *)
4067 obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4068 (*node)->aux = (void *) d;
4069 memset (d, 0, sizeof (*d));
4072 return d;
4075 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4076 it is already present. */
4078 static void
4079 maybe_push_queue (struct cgraph_node *node,
4080 cgraph_node_queue *queue_p, bool *in_queue_p)
4082 if (!*in_queue_p)
4084 *in_queue_p = true;
4085 queue_p->safe_push (node);
4089 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4090 code path. QUEUE are the basic blocks inside the transaction
4091 represented in REGION.
4093 Later in split_code_paths() we will add the conditional to choose
4094 between the two alternatives. */
4096 static void
4097 ipa_uninstrument_transaction (struct tm_region *region,
4098 vec<basic_block> queue)
4100 gimple transaction = region->transaction_stmt;
4101 basic_block transaction_bb = gimple_bb (transaction);
4102 int n = queue.length ();
4103 basic_block *new_bbs = XNEWVEC (basic_block, n);
4105 copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4106 true);
4107 edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4108 add_phi_args_after_copy (new_bbs, n, e);
4110 // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4111 // a) EDGE_FALLTHRU into the transaction
4112 // b) EDGE_TM_ABORT out of the transaction
4113 // c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4115 free (new_bbs);
4118 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4119 Queue all callees within block BB. */
4121 static void
4122 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4123 basic_block bb, bool for_clone)
4125 gimple_stmt_iterator gsi;
4127 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4129 gimple stmt = gsi_stmt (gsi);
4130 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4132 tree fndecl = gimple_call_fndecl (stmt);
4133 if (fndecl)
4135 struct tm_ipa_cg_data *d;
4136 unsigned *pcallers;
4137 struct cgraph_node *node;
4139 if (is_tm_ending_fndecl (fndecl))
4140 continue;
4141 if (find_tm_replacement_function (fndecl))
4142 continue;
4144 node = cgraph_node::get (fndecl);
4145 gcc_assert (node != NULL);
4146 d = get_cg_data (&node, true);
4148 pcallers = (for_clone ? &d->tm_callers_clone
4149 : &d->tm_callers_normal);
4150 *pcallers += 1;
4152 maybe_push_queue (node, callees_p, &d->in_callee_queue);
4158 /* Scan all calls in NODE that are within a transaction region,
4159 and push the resulting nodes into the callee queue. */
4161 static void
4162 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4163 cgraph_node_queue *callees_p)
4165 struct tm_region *r;
4167 d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4168 d->all_tm_regions = all_tm_regions;
4170 for (r = all_tm_regions; r; r = r->next)
4172 vec<basic_block> bbs;
4173 basic_block bb;
4174 unsigned i;
4176 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4177 d->transaction_blocks_normal, false);
4179 // Generate the uninstrumented code path for this transaction.
4180 ipa_uninstrument_transaction (r, bbs);
4182 FOR_EACH_VEC_ELT (bbs, i, bb)
4183 ipa_tm_scan_calls_block (callees_p, bb, false);
4185 bbs.release ();
4188 // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4189 // copying them, rather than forcing us to do this externally.
4190 cgraph_edge::rebuild_edges ();
4192 // ??? In ipa_uninstrument_transaction we don't try to update dominators
4193 // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4194 // Instead, just release dominators here so update_ssa recomputes them.
4195 free_dominance_info (CDI_DOMINATORS);
4197 // When building the uninstrumented code path, copy_bbs will have invoked
4198 // create_new_def_for starting an "ssa update context". There is only one
4199 // instance of this context, so resolve ssa updates before moving on to
4200 // the next function.
4201 update_ssa (TODO_update_ssa);
4204 /* Scan all calls in NODE as if this is the transactional clone,
4205 and push the destinations into the callee queue. */
4207 static void
4208 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4209 cgraph_node_queue *callees_p)
4211 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
4212 basic_block bb;
4214 FOR_EACH_BB_FN (bb, fn)
4215 ipa_tm_scan_calls_block (callees_p, bb, true);
4218 /* The function NODE has been detected to be irrevocable. Push all
4219 of its callers onto WORKLIST for the purpose of re-scanning them. */
4221 static void
4222 ipa_tm_note_irrevocable (struct cgraph_node *node,
4223 cgraph_node_queue *worklist_p)
4225 struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4226 struct cgraph_edge *e;
4228 d->is_irrevocable = true;
4230 for (e = node->callers; e ; e = e->next_caller)
4232 basic_block bb;
4233 struct cgraph_node *caller;
4235 /* Don't examine recursive calls. */
4236 if (e->caller == node)
4237 continue;
4238 /* Even if we think we can go irrevocable, believe the user
4239 above all. */
4240 if (is_tm_safe_or_pure (e->caller->decl))
4241 continue;
4243 caller = e->caller;
4244 d = get_cg_data (&caller, true);
4246 /* Check if the callee is in a transactional region. If so,
4247 schedule the function for normal re-scan as well. */
4248 bb = gimple_bb (e->call_stmt);
4249 gcc_assert (bb != NULL);
4250 if (d->transaction_blocks_normal
4251 && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4252 d->want_irr_scan_normal = true;
4254 maybe_push_queue (caller, worklist_p, &d->in_worklist);
4258 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4259 within the block is irrevocable. */
4261 static bool
4262 ipa_tm_scan_irr_block (basic_block bb)
4264 gimple_stmt_iterator gsi;
4265 tree fn;
4267 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4269 gimple stmt = gsi_stmt (gsi);
4270 switch (gimple_code (stmt))
4272 case GIMPLE_ASSIGN:
4273 if (gimple_assign_single_p (stmt))
4275 tree lhs = gimple_assign_lhs (stmt);
4276 tree rhs = gimple_assign_rhs1 (stmt);
4277 if (volatile_var_p (lhs) || volatile_var_p (rhs))
4278 return true;
4280 break;
4282 case GIMPLE_CALL:
4284 tree lhs = gimple_call_lhs (stmt);
4285 if (lhs && volatile_var_p (lhs))
4286 return true;
4288 if (is_tm_pure_call (stmt))
4289 break;
4291 fn = gimple_call_fn (stmt);
4293 /* Functions with the attribute are by definition irrevocable. */
4294 if (is_tm_irrevocable (fn))
4295 return true;
4297 /* For direct function calls, go ahead and check for replacement
4298 functions, or transitive irrevocable functions. For indirect
4299 functions, we'll ask the runtime. */
4300 if (TREE_CODE (fn) == ADDR_EXPR)
4302 struct tm_ipa_cg_data *d;
4303 struct cgraph_node *node;
4305 fn = TREE_OPERAND (fn, 0);
4306 if (is_tm_ending_fndecl (fn))
4307 break;
4308 if (find_tm_replacement_function (fn))
4309 break;
4311 node = cgraph_node::get (fn);
4312 d = get_cg_data (&node, true);
4314 /* Return true if irrevocable, but above all, believe
4315 the user. */
4316 if (d->is_irrevocable
4317 && !is_tm_safe_or_pure (fn))
4318 return true;
4320 break;
4323 case GIMPLE_ASM:
4324 /* ??? The Approved Method of indicating that an inline
4325 assembly statement is not relevant to the transaction
4326 is to wrap it in a __tm_waiver block. This is not
4327 yet implemented, so we can't check for it. */
4328 if (is_tm_safe (current_function_decl))
4330 tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4331 SET_EXPR_LOCATION (t, gimple_location (stmt));
4332 error ("%Kasm not allowed in %<transaction_safe%> function", t);
4334 return true;
4336 default:
4337 break;
4341 return false;
4344 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4345 for new irrevocable blocks, marking them in NEW_IRR. Don't bother
4346 scanning past OLD_IRR or EXIT_BLOCKS. */
4348 static bool
4349 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4350 bitmap old_irr, bitmap exit_blocks)
4352 bool any_new_irr = false;
4353 edge e;
4354 edge_iterator ei;
4355 bitmap visited_blocks = BITMAP_ALLOC (NULL);
4359 basic_block bb = pqueue->pop ();
4361 /* Don't re-scan blocks we know already are irrevocable. */
4362 if (old_irr && bitmap_bit_p (old_irr, bb->index))
4363 continue;
4365 if (ipa_tm_scan_irr_block (bb))
4367 bitmap_set_bit (new_irr, bb->index);
4368 any_new_irr = true;
4370 else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4372 FOR_EACH_EDGE (e, ei, bb->succs)
4373 if (!bitmap_bit_p (visited_blocks, e->dest->index))
4375 bitmap_set_bit (visited_blocks, e->dest->index);
4376 pqueue->safe_push (e->dest);
4380 while (!pqueue->is_empty ());
4382 BITMAP_FREE (visited_blocks);
4384 return any_new_irr;
4387 /* Propagate the irrevocable property both up and down the dominator tree.
4388 BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4389 TM regions; OLD_IRR are the results of a previous scan of the dominator
4390 tree which has been fully propagated; NEW_IRR is the set of new blocks
4391 which are gaining the irrevocable property during the current scan. */
4393 static void
4394 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4395 bitmap old_irr, bitmap exit_blocks)
4397 vec<basic_block> bbs;
4398 bitmap all_region_blocks;
4400 /* If this block is in the old set, no need to rescan. */
4401 if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4402 return;
4404 all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4405 bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4406 all_region_blocks, false);
4409 basic_block bb = bbs.pop ();
4410 bool this_irr = bitmap_bit_p (new_irr, bb->index);
4411 bool all_son_irr = false;
4412 edge_iterator ei;
4413 edge e;
4415 /* Propagate up. If my children are, I am too, but we must have
4416 at least one child that is. */
4417 if (!this_irr)
4419 FOR_EACH_EDGE (e, ei, bb->succs)
4421 if (!bitmap_bit_p (new_irr, e->dest->index))
4423 all_son_irr = false;
4424 break;
4426 else
4427 all_son_irr = true;
4429 if (all_son_irr)
4431 /* Add block to new_irr if it hasn't already been processed. */
4432 if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4434 bitmap_set_bit (new_irr, bb->index);
4435 this_irr = true;
4440 /* Propagate down to everyone we immediately dominate. */
4441 if (this_irr)
4443 basic_block son;
4444 for (son = first_dom_son (CDI_DOMINATORS, bb);
4445 son;
4446 son = next_dom_son (CDI_DOMINATORS, son))
4448 /* Make sure block is actually in a TM region, and it
4449 isn't already in old_irr. */
4450 if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4451 && bitmap_bit_p (all_region_blocks, son->index))
4452 bitmap_set_bit (new_irr, son->index);
4456 while (!bbs.is_empty ());
4458 BITMAP_FREE (all_region_blocks);
4459 bbs.release ();
4462 static void
4463 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4465 gimple_stmt_iterator gsi;
4467 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4469 gimple stmt = gsi_stmt (gsi);
4470 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4472 tree fndecl = gimple_call_fndecl (stmt);
4473 if (fndecl)
4475 struct tm_ipa_cg_data *d;
4476 unsigned *pcallers;
4477 struct cgraph_node *tnode;
4479 if (is_tm_ending_fndecl (fndecl))
4480 continue;
4481 if (find_tm_replacement_function (fndecl))
4482 continue;
4484 tnode = cgraph_node::get (fndecl);
4485 d = get_cg_data (&tnode, true);
4487 pcallers = (for_clone ? &d->tm_callers_clone
4488 : &d->tm_callers_normal);
4490 gcc_assert (*pcallers > 0);
4491 *pcallers -= 1;
4497 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4498 as well as other irrevocable actions such as inline assembly. Mark all
4499 such blocks as irrevocable and decrement the number of calls to
4500 transactional clones. Return true if, for the transactional clone, the
4501 entire function is irrevocable. */
4503 static bool
4504 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4506 struct tm_ipa_cg_data *d;
4507 bitmap new_irr, old_irr;
4508 bool ret = false;
4510 /* Builtin operators (operator new, and such). */
4511 if (DECL_STRUCT_FUNCTION (node->decl) == NULL
4512 || DECL_STRUCT_FUNCTION (node->decl)->cfg == NULL)
4513 return false;
4515 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4516 calculate_dominance_info (CDI_DOMINATORS);
4518 d = get_cg_data (&node, true);
4519 auto_vec<basic_block, 10> queue;
4520 new_irr = BITMAP_ALLOC (&tm_obstack);
4522 /* Scan each tm region, propagating irrevocable status through the tree. */
4523 if (for_clone)
4525 old_irr = d->irrevocable_blocks_clone;
4526 queue.quick_push (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
4527 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4529 ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
4530 new_irr,
4531 old_irr, NULL);
4532 ret = bitmap_bit_p (new_irr,
4533 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun))->index);
4536 else
4538 struct tm_region *region;
4540 old_irr = d->irrevocable_blocks_normal;
4541 for (region = d->all_tm_regions; region; region = region->next)
4543 queue.quick_push (region->entry_block);
4544 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4545 region->exit_blocks))
4546 ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4547 region->exit_blocks);
4551 /* If we found any new irrevocable blocks, reduce the call count for
4552 transactional clones within the irrevocable blocks. Save the new
4553 set of irrevocable blocks for next time. */
4554 if (!bitmap_empty_p (new_irr))
4556 bitmap_iterator bmi;
4557 unsigned i;
4559 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4560 ipa_tm_decrement_clone_counts (BASIC_BLOCK_FOR_FN (cfun, i),
4561 for_clone);
4563 if (old_irr)
4565 bitmap_ior_into (old_irr, new_irr);
4566 BITMAP_FREE (new_irr);
4568 else if (for_clone)
4569 d->irrevocable_blocks_clone = new_irr;
4570 else
4571 d->irrevocable_blocks_normal = new_irr;
4573 if (dump_file && new_irr)
4575 const char *dname;
4576 bitmap_iterator bmi;
4577 unsigned i;
4579 dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4580 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4581 fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4584 else
4585 BITMAP_FREE (new_irr);
4587 pop_cfun ();
4589 return ret;
4592 /* Return true if, for the transactional clone of NODE, any call
4593 may enter irrevocable mode. */
4595 static bool
4596 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4598 struct tm_ipa_cg_data *d;
4599 tree decl;
4600 unsigned flags;
4602 d = get_cg_data (&node, true);
4603 decl = node->decl;
4604 flags = flags_from_decl_or_type (decl);
4606 /* Handle some TM builtins. Ordinarily these aren't actually generated
4607 at this point, but handling these functions when written in by the
4608 user makes it easier to build unit tests. */
4609 if (flags & ECF_TM_BUILTIN)
4610 return false;
4612 /* Filter out all functions that are marked. */
4613 if (flags & ECF_TM_PURE)
4614 return false;
4615 if (is_tm_safe (decl))
4616 return false;
4617 if (is_tm_irrevocable (decl))
4618 return true;
4619 if (is_tm_callable (decl))
4620 return true;
4621 if (find_tm_replacement_function (decl))
4622 return true;
4624 /* If we aren't seeing the final version of the function we don't
4625 know what it will contain at runtime. */
4626 if (node->get_availability () < AVAIL_AVAILABLE)
4627 return true;
4629 /* If the function must go irrevocable, then of course true. */
4630 if (d->is_irrevocable)
4631 return true;
4633 /* If there are any blocks marked irrevocable, then the function
4634 as a whole may enter irrevocable. */
4635 if (d->irrevocable_blocks_clone)
4636 return true;
4638 /* We may have previously marked this function as tm_may_enter_irr;
4639 see pass_diagnose_tm_blocks. */
4640 if (node->local.tm_may_enter_irr)
4641 return true;
4643 /* Recurse on the main body for aliases. In general, this will
4644 result in one of the bits above being set so that we will not
4645 have to recurse next time. */
4646 if (node->alias)
4647 return ipa_tm_mayenterirr_function (cgraph_node::get (node->thunk.alias));
4649 /* What remains is unmarked local functions without items that force
4650 the function to go irrevocable. */
4651 return false;
4654 /* Diagnose calls from transaction_safe functions to unmarked
4655 functions that are determined to not be safe. */
4657 static void
4658 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4660 struct cgraph_edge *e;
4662 for (e = node->callees; e ; e = e->next_callee)
4663 if (!is_tm_callable (e->callee->decl)
4664 && e->callee->local.tm_may_enter_irr)
4665 error_at (gimple_location (e->call_stmt),
4666 "unsafe function call %qD within "
4667 "%<transaction_safe%> function", e->callee->decl);
4670 /* Diagnose call from atomic transactions to unmarked functions
4671 that are determined to not be safe. */
4673 static void
4674 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4675 struct tm_region *all_tm_regions)
4677 struct tm_region *r;
4679 for (r = all_tm_regions; r ; r = r->next)
4680 if (gimple_transaction_subcode (r->get_transaction_stmt ())
4681 & GTMA_IS_RELAXED)
4683 /* Atomic transactions can be nested inside relaxed. */
4684 if (r->inner)
4685 ipa_tm_diagnose_transaction (node, r->inner);
4687 else
4689 vec<basic_block> bbs;
4690 gimple_stmt_iterator gsi;
4691 basic_block bb;
4692 size_t i;
4694 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4695 r->irr_blocks, NULL, false);
4697 for (i = 0; bbs.iterate (i, &bb); ++i)
4698 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4700 gimple stmt = gsi_stmt (gsi);
4701 tree fndecl;
4703 if (gimple_code (stmt) == GIMPLE_ASM)
4705 error_at (gimple_location (stmt),
4706 "asm not allowed in atomic transaction");
4707 continue;
4710 if (!is_gimple_call (stmt))
4711 continue;
4712 fndecl = gimple_call_fndecl (stmt);
4714 /* Indirect function calls have been diagnosed already. */
4715 if (!fndecl)
4716 continue;
4718 /* Stop at the end of the transaction. */
4719 if (is_tm_ending_fndecl (fndecl))
4721 if (bitmap_bit_p (r->exit_blocks, bb->index))
4722 break;
4723 continue;
4726 /* Marked functions have been diagnosed already. */
4727 if (is_tm_pure_call (stmt))
4728 continue;
4729 if (is_tm_callable (fndecl))
4730 continue;
4732 if (cgraph_node::local_info (fndecl)->tm_may_enter_irr)
4733 error_at (gimple_location (stmt),
4734 "unsafe function call %qD within "
4735 "atomic transaction", fndecl);
4738 bbs.release ();
4742 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4743 OLD_DECL. The returned value is a freshly malloced pointer that
4744 should be freed by the caller. */
4746 static tree
4747 tm_mangle (tree old_asm_id)
4749 const char *old_asm_name;
4750 char *tm_name;
4751 void *alloc = NULL;
4752 struct demangle_component *dc;
4753 tree new_asm_id;
4755 /* Determine if the symbol is already a valid C++ mangled name. Do this
4756 even for C, which might be interfacing with C++ code via appropriately
4757 ugly identifiers. */
4758 /* ??? We could probably do just as well checking for "_Z" and be done. */
4759 old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4760 dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4762 if (dc == NULL)
4764 char length[8];
4766 do_unencoded:
4767 sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4768 tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4770 else
4772 old_asm_name += 2; /* Skip _Z */
4774 switch (dc->type)
4776 case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4777 case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4778 /* Don't play silly games, you! */
4779 goto do_unencoded;
4781 case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4782 /* I'd really like to know if we can ever be passed one of
4783 these from the C++ front end. The Logical Thing would
4784 seem that hidden-alias should be outer-most, so that we
4785 get hidden-alias of a transaction-clone and not vice-versa. */
4786 old_asm_name += 2;
4787 break;
4789 default:
4790 break;
4793 tm_name = concat ("_ZGTt", old_asm_name, NULL);
4795 free (alloc);
4797 new_asm_id = get_identifier (tm_name);
4798 free (tm_name);
4800 return new_asm_id;
4803 static inline void
4804 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4806 node->mark_force_output ();
4807 node->analyzed = true;
4810 static inline void
4811 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4813 node->forced_by_abi = true;
4814 node->analyzed = true;
4817 /* Callback data for ipa_tm_create_version_alias. */
4818 struct create_version_alias_info
4820 struct cgraph_node *old_node;
4821 tree new_decl;
4824 /* A subroutine of ipa_tm_create_version, called via
4825 cgraph_for_node_and_aliases. Create new tm clones for each of
4826 the existing aliases. */
4827 static bool
4828 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4830 struct create_version_alias_info *info
4831 = (struct create_version_alias_info *)data;
4832 tree old_decl, new_decl, tm_name;
4833 struct cgraph_node *new_node;
4835 if (!node->cpp_implicit_alias)
4836 return false;
4838 old_decl = node->decl;
4839 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4840 new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4841 TREE_CODE (old_decl), tm_name,
4842 TREE_TYPE (old_decl));
4844 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4845 SET_DECL_RTL (new_decl, NULL);
4847 /* Based loosely on C++'s make_alias_for(). */
4848 TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4849 DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4850 DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4851 TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4852 DECL_EXTERNAL (new_decl) = 0;
4853 DECL_ARTIFICIAL (new_decl) = 1;
4854 TREE_ADDRESSABLE (new_decl) = 1;
4855 TREE_USED (new_decl) = 1;
4856 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4858 /* Perform the same remapping to the comdat group. */
4859 if (DECL_ONE_ONLY (new_decl))
4860 varpool_node::get (new_decl)->set_comdat_group
4861 (tm_mangle (decl_comdat_group_id (old_decl)));
4863 new_node = cgraph_node::create_same_body_alias (new_decl, info->new_decl);
4864 new_node->tm_clone = true;
4865 new_node->externally_visible = info->old_node->externally_visible;
4866 new_node->no_reorder = info->old_node->no_reorder;
4867 /* ?? Do not traverse aliases here. */
4868 get_cg_data (&node, false)->clone = new_node;
4870 record_tm_clone_pair (old_decl, new_decl);
4872 if (info->old_node->force_output
4873 || info->old_node->ref_list.first_referring ())
4874 ipa_tm_mark_force_output_node (new_node);
4875 if (info->old_node->forced_by_abi)
4876 ipa_tm_mark_forced_by_abi_node (new_node);
4877 return false;
4880 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4881 appropriate for the transactional clone. */
4883 static void
4884 ipa_tm_create_version (struct cgraph_node *old_node)
4886 tree new_decl, old_decl, tm_name;
4887 struct cgraph_node *new_node;
4889 old_decl = old_node->decl;
4890 new_decl = copy_node (old_decl);
4892 /* DECL_ASSEMBLER_NAME needs to be set before we call
4893 cgraph_copy_node_for_versioning below, because cgraph_node will
4894 fill the assembler_name_hash. */
4895 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4896 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4897 SET_DECL_RTL (new_decl, NULL);
4898 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4900 /* Perform the same remapping to the comdat group. */
4901 if (DECL_ONE_ONLY (new_decl))
4902 varpool_node::get (new_decl)->set_comdat_group
4903 (tm_mangle (DECL_COMDAT_GROUP (old_decl)));
4905 gcc_assert (!old_node->ipa_transforms_to_apply.exists ());
4906 new_node = old_node->create_version_clone (new_decl, vNULL, NULL);
4907 new_node->local.local = false;
4908 new_node->externally_visible = old_node->externally_visible;
4909 new_node->lowered = true;
4910 new_node->tm_clone = 1;
4911 if (!old_node->implicit_section)
4912 new_node->set_section (old_node->get_section ());
4913 get_cg_data (&old_node, true)->clone = new_node;
4915 if (old_node->get_availability () >= AVAIL_INTERPOSABLE)
4917 /* Remap extern inline to static inline. */
4918 /* ??? Is it worth trying to use make_decl_one_only? */
4919 if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4921 DECL_EXTERNAL (new_decl) = 0;
4922 TREE_PUBLIC (new_decl) = 0;
4923 DECL_WEAK (new_decl) = 0;
4926 tree_function_versioning (old_decl, new_decl,
4927 NULL, false, NULL,
4928 false, NULL, NULL);
4931 record_tm_clone_pair (old_decl, new_decl);
4933 symtab->call_cgraph_insertion_hooks (new_node);
4934 if (old_node->force_output
4935 || old_node->ref_list.first_referring ())
4936 ipa_tm_mark_force_output_node (new_node);
4937 if (old_node->forced_by_abi)
4938 ipa_tm_mark_forced_by_abi_node (new_node);
4940 /* Do the same thing, but for any aliases of the original node. */
4942 struct create_version_alias_info data;
4943 data.old_node = old_node;
4944 data.new_decl = new_decl;
4945 old_node->call_for_symbol_thunks_and_aliases (ipa_tm_create_version_alias,
4946 &data, true);
4950 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB. */
4952 static void
4953 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4954 basic_block bb)
4956 gimple_stmt_iterator gsi;
4957 gcall *g;
4959 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4961 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4962 1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4964 split_block_after_labels (bb);
4965 gsi = gsi_after_labels (bb);
4966 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4968 node->create_edge (cgraph_node::get_create
4969 (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4970 g, 0,
4971 compute_call_stmt_bb_frequency (node->decl,
4972 gimple_bb (g)));
4975 /* Construct a call to TM_GETTMCLONE and insert it before GSI. */
4977 static bool
4978 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4979 struct tm_region *region,
4980 gimple_stmt_iterator *gsi, gcall *stmt)
4982 tree gettm_fn, ret, old_fn, callfn;
4983 gcall *g;
4984 gassign *g2;
4985 bool safe;
4987 old_fn = gimple_call_fn (stmt);
4989 if (TREE_CODE (old_fn) == ADDR_EXPR)
4991 tree fndecl = TREE_OPERAND (old_fn, 0);
4992 tree clone = get_tm_clone_pair (fndecl);
4994 /* By transforming the call into a TM_GETTMCLONE, we are
4995 technically taking the address of the original function and
4996 its clone. Explain this so inlining will know this function
4997 is needed. */
4998 cgraph_node::get (fndecl)->mark_address_taken () ;
4999 if (clone)
5000 cgraph_node::get (clone)->mark_address_taken ();
5003 safe = is_tm_safe (TREE_TYPE (old_fn));
5004 gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
5005 : BUILT_IN_TM_GETTMCLONE_IRR);
5006 ret = create_tmp_var (ptr_type_node);
5008 if (!safe)
5009 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
5011 /* Discard OBJ_TYPE_REF, since we weren't able to fold it. */
5012 if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
5013 old_fn = OBJ_TYPE_REF_EXPR (old_fn);
5015 g = gimple_build_call (gettm_fn, 1, old_fn);
5016 ret = make_ssa_name (ret, g);
5017 gimple_call_set_lhs (g, ret);
5019 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5021 node->create_edge (cgraph_node::get_create (gettm_fn), g, 0,
5022 compute_call_stmt_bb_frequency (node->decl,
5023 gimple_bb (g)));
5025 /* Cast return value from tm_gettmclone* into appropriate function
5026 pointer. */
5027 callfn = create_tmp_var (TREE_TYPE (old_fn));
5028 g2 = gimple_build_assign (callfn,
5029 fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5030 callfn = make_ssa_name (callfn, g2);
5031 gimple_assign_set_lhs (g2, callfn);
5032 gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5034 /* ??? This is a hack to preserve the NOTHROW bit on the call,
5035 which we would have derived from the decl. Failure to save
5036 this bit means we might have to split the basic block. */
5037 if (gimple_call_nothrow_p (stmt))
5038 gimple_call_set_nothrow (stmt, true);
5040 gimple_call_set_fn (stmt, callfn);
5042 /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5043 for a call statement. Fix it. */
5045 tree lhs = gimple_call_lhs (stmt);
5046 tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5047 if (lhs
5048 && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5050 tree temp;
5052 temp = create_tmp_reg (rettype);
5053 gimple_call_set_lhs (stmt, temp);
5055 g2 = gimple_build_assign (lhs,
5056 fold_build1 (VIEW_CONVERT_EXPR,
5057 TREE_TYPE (lhs), temp));
5058 gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5062 update_stmt (stmt);
5063 cgraph_edge *e = cgraph_node::get (current_function_decl)->get_edge (stmt);
5064 if (e && e->indirect_info)
5065 e->indirect_info->polymorphic = false;
5067 return true;
5070 /* Helper function for ipa_tm_transform_calls*. Given a call
5071 statement in GSI which resides inside transaction REGION, redirect
5072 the call to either its wrapper function, or its clone. */
5074 static void
5075 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5076 struct tm_region *region,
5077 gimple_stmt_iterator *gsi,
5078 bool *need_ssa_rename_p)
5080 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
5081 struct cgraph_node *new_node;
5082 struct cgraph_edge *e = node->get_edge (stmt);
5083 tree fndecl = gimple_call_fndecl (stmt);
5085 /* For indirect calls, pass the address through the runtime. */
5086 if (fndecl == NULL)
5088 *need_ssa_rename_p |=
5089 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5090 return;
5093 /* Handle some TM builtins. Ordinarily these aren't actually generated
5094 at this point, but handling these functions when written in by the
5095 user makes it easier to build unit tests. */
5096 if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5097 return;
5099 /* Fixup recursive calls inside clones. */
5100 /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5101 for recursion but not update the call statements themselves? */
5102 if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5104 gimple_call_set_fndecl (stmt, current_function_decl);
5105 return;
5108 /* If there is a replacement, use it. */
5109 fndecl = find_tm_replacement_function (fndecl);
5110 if (fndecl)
5112 new_node = cgraph_node::get_create (fndecl);
5114 /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5116 We can't do this earlier in record_tm_replacement because
5117 cgraph_remove_unreachable_nodes is called before we inject
5118 references to the node. Further, we can't do this in some
5119 nice central place in ipa_tm_execute because we don't have
5120 the exact list of wrapper functions that would be used.
5121 Marking more wrappers than necessary results in the creation
5122 of unnecessary cgraph_nodes, which can cause some of the
5123 other IPA passes to crash.
5125 We do need to mark these nodes so that we get the proper
5126 result in expand_call_tm. */
5127 /* ??? This seems broken. How is it that we're marking the
5128 CALLEE as may_enter_irr? Surely we should be marking the
5129 CALLER. Also note that find_tm_replacement_function also
5130 contains mappings into the TM runtime, e.g. memcpy. These
5131 we know won't go irrevocable. */
5132 new_node->local.tm_may_enter_irr = 1;
5134 else
5136 struct tm_ipa_cg_data *d;
5137 struct cgraph_node *tnode = e->callee;
5139 d = get_cg_data (&tnode, true);
5140 new_node = d->clone;
5142 /* As we've already skipped pure calls and appropriate builtins,
5143 and we've already marked irrevocable blocks, if we can't come
5144 up with a static replacement, then ask the runtime. */
5145 if (new_node == NULL)
5147 *need_ssa_rename_p |=
5148 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5149 return;
5152 fndecl = new_node->decl;
5155 e->redirect_callee (new_node);
5156 gimple_call_set_fndecl (stmt, fndecl);
5159 /* Helper function for ipa_tm_transform_calls. For a given BB,
5160 install calls to tm_irrevocable when IRR_BLOCKS are reached,
5161 redirect other calls to the generated transactional clone. */
5163 static bool
5164 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5165 basic_block bb, bitmap irr_blocks)
5167 gimple_stmt_iterator gsi;
5168 bool need_ssa_rename = false;
5170 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5172 ipa_tm_insert_irr_call (node, region, bb);
5173 return true;
5176 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5178 gimple stmt = gsi_stmt (gsi);
5180 if (!is_gimple_call (stmt))
5181 continue;
5182 if (is_tm_pure_call (stmt))
5183 continue;
5185 /* Redirect edges to the appropriate replacement or clone. */
5186 ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5189 return need_ssa_rename;
5192 /* Walk the CFG for REGION, beginning at BB. Install calls to
5193 tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5194 the generated transactional clone. */
5196 static bool
5197 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5198 basic_block bb, bitmap irr_blocks)
5200 bool need_ssa_rename = false;
5201 edge e;
5202 edge_iterator ei;
5203 auto_vec<basic_block> queue;
5204 bitmap visited_blocks = BITMAP_ALLOC (NULL);
5206 queue.safe_push (bb);
5209 bb = queue.pop ();
5211 need_ssa_rename |=
5212 ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5214 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5215 continue;
5217 if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5218 continue;
5220 FOR_EACH_EDGE (e, ei, bb->succs)
5221 if (!bitmap_bit_p (visited_blocks, e->dest->index))
5223 bitmap_set_bit (visited_blocks, e->dest->index);
5224 queue.safe_push (e->dest);
5227 while (!queue.is_empty ());
5229 BITMAP_FREE (visited_blocks);
5231 return need_ssa_rename;
5234 /* Transform the calls within the TM regions within NODE. */
5236 static void
5237 ipa_tm_transform_transaction (struct cgraph_node *node)
5239 struct tm_ipa_cg_data *d;
5240 struct tm_region *region;
5241 bool need_ssa_rename = false;
5243 d = get_cg_data (&node, true);
5245 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5246 calculate_dominance_info (CDI_DOMINATORS);
5248 for (region = d->all_tm_regions; region; region = region->next)
5250 /* If we're sure to go irrevocable, don't transform anything. */
5251 if (d->irrevocable_blocks_normal
5252 && bitmap_bit_p (d->irrevocable_blocks_normal,
5253 region->entry_block->index))
5255 transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5256 | GTMA_MAY_ENTER_IRREVOCABLE
5257 | GTMA_HAS_NO_INSTRUMENTATION);
5258 continue;
5261 need_ssa_rename |=
5262 ipa_tm_transform_calls (node, region, region->entry_block,
5263 d->irrevocable_blocks_normal);
5266 if (need_ssa_rename)
5267 update_ssa (TODO_update_ssa_only_virtuals);
5269 pop_cfun ();
5272 /* Transform the calls within the transactional clone of NODE. */
5274 static void
5275 ipa_tm_transform_clone (struct cgraph_node *node)
5277 struct tm_ipa_cg_data *d;
5278 bool need_ssa_rename;
5280 d = get_cg_data (&node, true);
5282 /* If this function makes no calls and has no irrevocable blocks,
5283 then there's nothing to do. */
5284 /* ??? Remove non-aborting top-level transactions. */
5285 if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5286 return;
5288 push_cfun (DECL_STRUCT_FUNCTION (d->clone->decl));
5289 calculate_dominance_info (CDI_DOMINATORS);
5291 need_ssa_rename =
5292 ipa_tm_transform_calls (d->clone, NULL,
5293 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
5294 d->irrevocable_blocks_clone);
5296 if (need_ssa_rename)
5297 update_ssa (TODO_update_ssa_only_virtuals);
5299 pop_cfun ();
5302 /* Main entry point for the transactional memory IPA pass. */
5304 static unsigned int
5305 ipa_tm_execute (void)
5307 cgraph_node_queue tm_callees = cgraph_node_queue ();
5308 /* List of functions that will go irrevocable. */
5309 cgraph_node_queue irr_worklist = cgraph_node_queue ();
5311 struct cgraph_node *node;
5312 struct tm_ipa_cg_data *d;
5313 enum availability a;
5314 unsigned int i;
5316 #ifdef ENABLE_CHECKING
5317 cgraph_node::verify_cgraph_nodes ();
5318 #endif
5320 bitmap_obstack_initialize (&tm_obstack);
5321 initialize_original_copy_tables ();
5323 /* For all local functions marked tm_callable, queue them. */
5324 FOR_EACH_DEFINED_FUNCTION (node)
5325 if (is_tm_callable (node->decl)
5326 && node->get_availability () >= AVAIL_INTERPOSABLE)
5328 d = get_cg_data (&node, true);
5329 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5332 /* For all local reachable functions... */
5333 FOR_EACH_DEFINED_FUNCTION (node)
5334 if (node->lowered
5335 && node->get_availability () >= AVAIL_INTERPOSABLE)
5337 /* ... marked tm_pure, record that fact for the runtime by
5338 indicating that the pure function is its own tm_callable.
5339 No need to do this if the function's address can't be taken. */
5340 if (is_tm_pure (node->decl))
5342 if (!node->local.local)
5343 record_tm_clone_pair (node->decl, node->decl);
5344 continue;
5347 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5348 calculate_dominance_info (CDI_DOMINATORS);
5350 tm_region_init (NULL);
5351 if (all_tm_regions)
5353 d = get_cg_data (&node, true);
5355 /* Scan for calls that are in each transaction, and
5356 generate the uninstrumented code path. */
5357 ipa_tm_scan_calls_transaction (d, &tm_callees);
5359 /* Put it in the worklist so we can scan the function
5360 later (ipa_tm_scan_irr_function) and mark the
5361 irrevocable blocks. */
5362 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5363 d->want_irr_scan_normal = true;
5366 pop_cfun ();
5369 /* For every local function on the callee list, scan as if we will be
5370 creating a transactional clone, queueing all new functions we find
5371 along the way. */
5372 for (i = 0; i < tm_callees.length (); ++i)
5374 node = tm_callees[i];
5375 a = node->get_availability ();
5376 d = get_cg_data (&node, true);
5378 /* Put it in the worklist so we can scan the function later
5379 (ipa_tm_scan_irr_function) and mark the irrevocable
5380 blocks. */
5381 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5383 /* Some callees cannot be arbitrarily cloned. These will always be
5384 irrevocable. Mark these now, so that we need not scan them. */
5385 if (is_tm_irrevocable (node->decl))
5386 ipa_tm_note_irrevocable (node, &irr_worklist);
5387 else if (a <= AVAIL_NOT_AVAILABLE
5388 && !is_tm_safe_or_pure (node->decl))
5389 ipa_tm_note_irrevocable (node, &irr_worklist);
5390 else if (a >= AVAIL_INTERPOSABLE)
5392 if (!tree_versionable_function_p (node->decl))
5393 ipa_tm_note_irrevocable (node, &irr_worklist);
5394 else if (!d->is_irrevocable)
5396 /* If this is an alias, make sure its base is queued as well.
5397 we need not scan the callees now, as the base will do. */
5398 if (node->alias)
5400 node = cgraph_node::get (node->thunk.alias);
5401 d = get_cg_data (&node, true);
5402 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5403 continue;
5406 /* Add all nodes called by this function into
5407 tm_callees as well. */
5408 ipa_tm_scan_calls_clone (node, &tm_callees);
5413 /* Iterate scans until no more work to be done. Prefer not to use
5414 vec::pop because the worklist tends to follow a breadth-first
5415 search of the callgraph, which should allow convergance with a
5416 minimum number of scans. But we also don't want the worklist
5417 array to grow without bound, so we shift the array up periodically. */
5418 for (i = 0; i < irr_worklist.length (); ++i)
5420 if (i > 256 && i == irr_worklist.length () / 8)
5422 irr_worklist.block_remove (0, i);
5423 i = 0;
5426 node = irr_worklist[i];
5427 d = get_cg_data (&node, true);
5428 d->in_worklist = false;
5430 if (d->want_irr_scan_normal)
5432 d->want_irr_scan_normal = false;
5433 ipa_tm_scan_irr_function (node, false);
5435 if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5436 ipa_tm_note_irrevocable (node, &irr_worklist);
5439 /* For every function on the callee list, collect the tm_may_enter_irr
5440 bit on the node. */
5441 irr_worklist.truncate (0);
5442 for (i = 0; i < tm_callees.length (); ++i)
5444 node = tm_callees[i];
5445 if (ipa_tm_mayenterirr_function (node))
5447 d = get_cg_data (&node, true);
5448 gcc_assert (d->in_worklist == false);
5449 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5453 /* Propagate the tm_may_enter_irr bit to callers until stable. */
5454 for (i = 0; i < irr_worklist.length (); ++i)
5456 struct cgraph_node *caller;
5457 struct cgraph_edge *e;
5458 struct ipa_ref *ref;
5460 if (i > 256 && i == irr_worklist.length () / 8)
5462 irr_worklist.block_remove (0, i);
5463 i = 0;
5466 node = irr_worklist[i];
5467 d = get_cg_data (&node, true);
5468 d->in_worklist = false;
5469 node->local.tm_may_enter_irr = true;
5471 /* Propagate back to normal callers. */
5472 for (e = node->callers; e ; e = e->next_caller)
5474 caller = e->caller;
5475 if (!is_tm_safe_or_pure (caller->decl)
5476 && !caller->local.tm_may_enter_irr)
5478 d = get_cg_data (&caller, true);
5479 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5483 /* Propagate back to referring aliases as well. */
5484 FOR_EACH_ALIAS (node, ref)
5486 caller = dyn_cast<cgraph_node *> (ref->referring);
5487 if (!caller->local.tm_may_enter_irr)
5489 /* ?? Do not traverse aliases here. */
5490 d = get_cg_data (&caller, false);
5491 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5496 /* Now validate all tm_safe functions, and all atomic regions in
5497 other functions. */
5498 FOR_EACH_DEFINED_FUNCTION (node)
5499 if (node->lowered
5500 && node->get_availability () >= AVAIL_INTERPOSABLE)
5502 d = get_cg_data (&node, true);
5503 if (is_tm_safe (node->decl))
5504 ipa_tm_diagnose_tm_safe (node);
5505 else if (d->all_tm_regions)
5506 ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5509 /* Create clones. Do those that are not irrevocable and have a
5510 positive call count. Do those publicly visible functions that
5511 the user directed us to clone. */
5512 for (i = 0; i < tm_callees.length (); ++i)
5514 bool doit = false;
5516 node = tm_callees[i];
5517 if (node->cpp_implicit_alias)
5518 continue;
5520 a = node->get_availability ();
5521 d = get_cg_data (&node, true);
5523 if (a <= AVAIL_NOT_AVAILABLE)
5524 doit = is_tm_callable (node->decl);
5525 else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
5526 doit = true;
5527 else if (!d->is_irrevocable
5528 && d->tm_callers_normal + d->tm_callers_clone > 0)
5529 doit = true;
5531 if (doit)
5532 ipa_tm_create_version (node);
5535 /* Redirect calls to the new clones, and insert irrevocable marks. */
5536 for (i = 0; i < tm_callees.length (); ++i)
5538 node = tm_callees[i];
5539 if (node->analyzed)
5541 d = get_cg_data (&node, true);
5542 if (d->clone)
5543 ipa_tm_transform_clone (node);
5546 FOR_EACH_DEFINED_FUNCTION (node)
5547 if (node->lowered
5548 && node->get_availability () >= AVAIL_INTERPOSABLE)
5550 d = get_cg_data (&node, true);
5551 if (d->all_tm_regions)
5552 ipa_tm_transform_transaction (node);
5555 /* Free and clear all data structures. */
5556 tm_callees.release ();
5557 irr_worklist.release ();
5558 bitmap_obstack_release (&tm_obstack);
5559 free_original_copy_tables ();
5561 FOR_EACH_FUNCTION (node)
5562 node->aux = NULL;
5564 #ifdef ENABLE_CHECKING
5565 cgraph_node::verify_cgraph_nodes ();
5566 #endif
5568 return 0;
5571 static const pass_data pass_data_ipa_tm =
5573 SIMPLE_IPA_PASS, /* type */
5574 "tmipa", /* name */
5575 OPTGROUP_NONE, /* optinfo_flags */
5576 TV_TRANS_MEM, /* tv_id */
5577 ( PROP_ssa | PROP_cfg ), /* properties_required */
5578 0, /* properties_provided */
5579 0, /* properties_destroyed */
5580 0, /* todo_flags_start */
5581 0, /* todo_flags_finish */
5584 class pass_ipa_tm GCC_FINAL : public simple_ipa_opt_pass
5586 public:
5587 pass_ipa_tm (gcc::context *ctxt)
5588 : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5591 /* opt_pass methods: */
5592 virtual bool gate (function *) { return flag_tm; }
5593 virtual unsigned int execute (function *) { return ipa_tm_execute (); }
5595 }; // class pass_ipa_tm
5597 simple_ipa_opt_pass *
5598 make_pass_ipa_tm (gcc::context *ctxt)
5600 return new pass_ipa_tm (ctxt);
5603 #include "gt-trans-mem.h"