2014-11-18 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / gcc / trans-mem.c
blob9899e7b54a89fa6637285c6cf524c6c4a6e1b2b5
1 /* Passes for transactional memory support.
2 Copyright (C) 2008-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hash-table.h"
24 #include "tree.h"
25 #include "predict.h"
26 #include "vec.h"
27 #include "hashtab.h"
28 #include "hash-set.h"
29 #include "machmode.h"
30 #include "tm.h"
31 #include "hard-reg-set.h"
32 #include "input.h"
33 #include "function.h"
34 #include "dominance.h"
35 #include "cfg.h"
36 #include "basic-block.h"
37 #include "tree-ssa-alias.h"
38 #include "internal-fn.h"
39 #include "tree-eh.h"
40 #include "gimple-expr.h"
41 #include "is-a.h"
42 #include "gimple.h"
43 #include "calls.h"
44 #include "rtl.h"
45 #include "emit-rtl.h"
46 #include "gimplify.h"
47 #include "gimple-iterator.h"
48 #include "gimplify-me.h"
49 #include "gimple-walk.h"
50 #include "gimple-ssa.h"
51 #include "hash-map.h"
52 #include "plugin-api.h"
53 #include "ipa-ref.h"
54 #include "cgraph.h"
55 #include "tree-cfg.h"
56 #include "stringpool.h"
57 #include "tree-ssanames.h"
58 #include "tree-into-ssa.h"
59 #include "tree-pass.h"
60 #include "tree-inline.h"
61 #include "diagnostic-core.h"
62 #include "demangle.h"
63 #include "output.h"
64 #include "trans-mem.h"
65 #include "params.h"
66 #include "target.h"
67 #include "langhooks.h"
68 #include "gimple-pretty-print.h"
69 #include "cfgloop.h"
70 #include "tree-ssa-address.h"
73 #define A_RUNINSTRUMENTEDCODE 0x0001
74 #define A_RUNUNINSTRUMENTEDCODE 0x0002
75 #define A_SAVELIVEVARIABLES 0x0004
76 #define A_RESTORELIVEVARIABLES 0x0008
77 #define A_ABORTTRANSACTION 0x0010
79 #define AR_USERABORT 0x0001
80 #define AR_USERRETRY 0x0002
81 #define AR_TMCONFLICT 0x0004
82 #define AR_EXCEPTIONBLOCKABORT 0x0008
83 #define AR_OUTERABORT 0x0010
85 #define MODE_SERIALIRREVOCABLE 0x0000
88 /* The representation of a transaction changes several times during the
89 lowering process. In the beginning, in the front-end we have the
90 GENERIC tree TRANSACTION_EXPR. For example,
92 __transaction {
93 local++;
94 if (++global == 10)
95 __tm_abort;
98 During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
99 trivially replaced with a GIMPLE_TRANSACTION node.
101 During pass_lower_tm, we examine the body of transactions looking
102 for aborts. Transactions that do not contain an abort may be
103 merged into an outer transaction. We also add a TRY-FINALLY node
104 to arrange for the transaction to be committed on any exit.
106 [??? Think about how this arrangement affects throw-with-commit
107 and throw-with-abort operations. In this case we want the TRY to
108 handle gotos, but not to catch any exceptions because the transaction
109 will already be closed.]
111 GIMPLE_TRANSACTION [label=NULL] {
112 try {
113 local = local + 1;
114 t0 = global;
115 t1 = t0 + 1;
116 global = t1;
117 if (t1 == 10)
118 __builtin___tm_abort ();
119 } finally {
120 __builtin___tm_commit ();
124 During pass_lower_eh, we create EH regions for the transactions,
125 intermixed with the regular EH stuff. This gives us a nice persistent
126 mapping (all the way through rtl) from transactional memory operation
127 back to the transaction, which allows us to get the abnormal edges
128 correct to model transaction aborts and restarts:
130 GIMPLE_TRANSACTION [label=over]
131 local = local + 1;
132 t0 = global;
133 t1 = t0 + 1;
134 global = t1;
135 if (t1 == 10)
136 __builtin___tm_abort ();
137 __builtin___tm_commit ();
138 over:
140 This is the end of all_lowering_passes, and so is what is present
141 during the IPA passes, and through all of the optimization passes.
143 During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
144 functions and mark functions for cloning.
146 At the end of gimple optimization, before exiting SSA form,
147 pass_tm_edges replaces statements that perform transactional
148 memory operations with the appropriate TM builtins, and swap
149 out function calls with their transactional clones. At this
150 point we introduce the abnormal transaction restart edges and
151 complete lowering of the GIMPLE_TRANSACTION node.
153 x = __builtin___tm_start (MAY_ABORT);
154 eh_label:
155 if (x & abort_transaction)
156 goto over;
157 local = local + 1;
158 t0 = __builtin___tm_load (global);
159 t1 = t0 + 1;
160 __builtin___tm_store (&global, t1);
161 if (t1 == 10)
162 __builtin___tm_abort ();
163 __builtin___tm_commit ();
164 over:
167 static void *expand_regions (struct tm_region *,
168 void *(*callback)(struct tm_region *, void *),
169 void *, bool);
172 /* Return the attributes we want to examine for X, or NULL if it's not
173 something we examine. We look at function types, but allow pointers
174 to function types and function decls and peek through. */
176 static tree
177 get_attrs_for (const_tree x)
179 switch (TREE_CODE (x))
181 case FUNCTION_DECL:
182 return TYPE_ATTRIBUTES (TREE_TYPE (x));
183 break;
185 default:
186 if (TYPE_P (x))
187 return NULL;
188 x = TREE_TYPE (x);
189 if (TREE_CODE (x) != POINTER_TYPE)
190 return NULL;
191 /* FALLTHRU */
193 case POINTER_TYPE:
194 x = TREE_TYPE (x);
195 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
196 return NULL;
197 /* FALLTHRU */
199 case FUNCTION_TYPE:
200 case METHOD_TYPE:
201 return TYPE_ATTRIBUTES (x);
205 /* Return true if X has been marked TM_PURE. */
207 bool
208 is_tm_pure (const_tree x)
210 unsigned flags;
212 switch (TREE_CODE (x))
214 case FUNCTION_DECL:
215 case FUNCTION_TYPE:
216 case METHOD_TYPE:
217 break;
219 default:
220 if (TYPE_P (x))
221 return false;
222 x = TREE_TYPE (x);
223 if (TREE_CODE (x) != POINTER_TYPE)
224 return false;
225 /* FALLTHRU */
227 case POINTER_TYPE:
228 x = TREE_TYPE (x);
229 if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
230 return false;
231 break;
234 flags = flags_from_decl_or_type (x);
235 return (flags & ECF_TM_PURE) != 0;
238 /* Return true if X has been marked TM_IRREVOCABLE. */
240 static bool
241 is_tm_irrevocable (tree x)
243 tree attrs = get_attrs_for (x);
245 if (attrs && lookup_attribute ("transaction_unsafe", attrs))
246 return true;
248 /* A call to the irrevocable builtin is by definition,
249 irrevocable. */
250 if (TREE_CODE (x) == ADDR_EXPR)
251 x = TREE_OPERAND (x, 0);
252 if (TREE_CODE (x) == FUNCTION_DECL
253 && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
254 && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
255 return true;
257 return false;
260 /* Return true if X has been marked TM_SAFE. */
262 bool
263 is_tm_safe (const_tree x)
265 if (flag_tm)
267 tree attrs = get_attrs_for (x);
268 if (attrs)
270 if (lookup_attribute ("transaction_safe", attrs))
271 return true;
272 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
273 return true;
276 return false;
279 /* Return true if CALL is const, or tm_pure. */
281 static bool
282 is_tm_pure_call (gimple call)
284 tree fn = gimple_call_fn (call);
286 if (TREE_CODE (fn) == ADDR_EXPR)
288 fn = TREE_OPERAND (fn, 0);
289 gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
291 else
292 fn = TREE_TYPE (fn);
294 return is_tm_pure (fn);
297 /* Return true if X has been marked TM_CALLABLE. */
299 static bool
300 is_tm_callable (tree x)
302 tree attrs = get_attrs_for (x);
303 if (attrs)
305 if (lookup_attribute ("transaction_callable", attrs))
306 return true;
307 if (lookup_attribute ("transaction_safe", attrs))
308 return true;
309 if (lookup_attribute ("transaction_may_cancel_outer", attrs))
310 return true;
312 return false;
315 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER. */
317 bool
318 is_tm_may_cancel_outer (tree x)
320 tree attrs = get_attrs_for (x);
321 if (attrs)
322 return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
323 return false;
326 /* Return true for built in functions that "end" a transaction. */
328 bool
329 is_tm_ending_fndecl (tree fndecl)
331 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
332 switch (DECL_FUNCTION_CODE (fndecl))
334 case BUILT_IN_TM_COMMIT:
335 case BUILT_IN_TM_COMMIT_EH:
336 case BUILT_IN_TM_ABORT:
337 case BUILT_IN_TM_IRREVOCABLE:
338 return true;
339 default:
340 break;
343 return false;
346 /* Return true if STMT is a built in function call that "ends" a
347 transaction. */
349 bool
350 is_tm_ending (gimple stmt)
352 tree fndecl;
354 if (gimple_code (stmt) != GIMPLE_CALL)
355 return false;
357 fndecl = gimple_call_fndecl (stmt);
358 return (fndecl != NULL_TREE
359 && is_tm_ending_fndecl (fndecl));
362 /* Return true if STMT is a TM load. */
364 static bool
365 is_tm_load (gimple stmt)
367 tree fndecl;
369 if (gimple_code (stmt) != GIMPLE_CALL)
370 return false;
372 fndecl = gimple_call_fndecl (stmt);
373 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
374 && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
377 /* Same as above, but for simple TM loads, that is, not the
378 after-write, after-read, etc optimized variants. */
380 static bool
381 is_tm_simple_load (gimple stmt)
383 tree fndecl;
385 if (gimple_code (stmt) != GIMPLE_CALL)
386 return false;
388 fndecl = gimple_call_fndecl (stmt);
389 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
391 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
392 return (fcode == BUILT_IN_TM_LOAD_1
393 || fcode == BUILT_IN_TM_LOAD_2
394 || fcode == BUILT_IN_TM_LOAD_4
395 || fcode == BUILT_IN_TM_LOAD_8
396 || fcode == BUILT_IN_TM_LOAD_FLOAT
397 || fcode == BUILT_IN_TM_LOAD_DOUBLE
398 || fcode == BUILT_IN_TM_LOAD_LDOUBLE
399 || fcode == BUILT_IN_TM_LOAD_M64
400 || fcode == BUILT_IN_TM_LOAD_M128
401 || fcode == BUILT_IN_TM_LOAD_M256);
403 return false;
406 /* Return true if STMT is a TM store. */
408 static bool
409 is_tm_store (gimple stmt)
411 tree fndecl;
413 if (gimple_code (stmt) != GIMPLE_CALL)
414 return false;
416 fndecl = gimple_call_fndecl (stmt);
417 return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
418 && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
421 /* Same as above, but for simple TM stores, that is, not the
422 after-write, after-read, etc optimized variants. */
424 static bool
425 is_tm_simple_store (gimple stmt)
427 tree fndecl;
429 if (gimple_code (stmt) != GIMPLE_CALL)
430 return false;
432 fndecl = gimple_call_fndecl (stmt);
433 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
435 enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
436 return (fcode == BUILT_IN_TM_STORE_1
437 || fcode == BUILT_IN_TM_STORE_2
438 || fcode == BUILT_IN_TM_STORE_4
439 || fcode == BUILT_IN_TM_STORE_8
440 || fcode == BUILT_IN_TM_STORE_FLOAT
441 || fcode == BUILT_IN_TM_STORE_DOUBLE
442 || fcode == BUILT_IN_TM_STORE_LDOUBLE
443 || fcode == BUILT_IN_TM_STORE_M64
444 || fcode == BUILT_IN_TM_STORE_M128
445 || fcode == BUILT_IN_TM_STORE_M256);
447 return false;
450 /* Return true if FNDECL is BUILT_IN_TM_ABORT. */
452 static bool
453 is_tm_abort (tree fndecl)
455 return (fndecl
456 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
457 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
460 /* Build a GENERIC tree for a user abort. This is called by front ends
461 while transforming the __tm_abort statement. */
463 tree
464 build_tm_abort_call (location_t loc, bool is_outer)
466 return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
467 build_int_cst (integer_type_node,
468 AR_USERABORT
469 | (is_outer ? AR_OUTERABORT : 0)));
472 /* Map for aribtrary function replacement under TM, as created
473 by the tm_wrap attribute. */
475 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
476 htab_t tm_wrap_map;
478 void
479 record_tm_replacement (tree from, tree to)
481 struct tree_map **slot, *h;
483 /* Do not inline wrapper functions that will get replaced in the TM
484 pass.
486 Suppose you have foo() that will get replaced into tmfoo(). Make
487 sure the inliner doesn't try to outsmart us and inline foo()
488 before we get a chance to do the TM replacement. */
489 DECL_UNINLINABLE (from) = 1;
491 if (tm_wrap_map == NULL)
492 tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
494 h = ggc_alloc<tree_map> ();
495 h->hash = htab_hash_pointer (from);
496 h->base.from = from;
497 h->to = to;
499 slot = (struct tree_map **)
500 htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
501 *slot = h;
504 /* Return a TM-aware replacement function for DECL. */
506 static tree
507 find_tm_replacement_function (tree fndecl)
509 if (tm_wrap_map)
511 struct tree_map *h, in;
513 in.base.from = fndecl;
514 in.hash = htab_hash_pointer (fndecl);
515 h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
516 if (h)
517 return h->to;
520 /* ??? We may well want TM versions of most of the common <string.h>
521 functions. For now, we've already these two defined. */
522 /* Adjust expand_call_tm() attributes as necessary for the cases
523 handled here: */
524 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
525 switch (DECL_FUNCTION_CODE (fndecl))
527 case BUILT_IN_MEMCPY:
528 return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
529 case BUILT_IN_MEMMOVE:
530 return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
531 case BUILT_IN_MEMSET:
532 return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
533 default:
534 return NULL;
537 return NULL;
540 /* When appropriate, record TM replacement for memory allocation functions.
542 FROM is the FNDECL to wrap. */
543 void
544 tm_malloc_replacement (tree from)
546 const char *str;
547 tree to;
549 if (TREE_CODE (from) != FUNCTION_DECL)
550 return;
552 /* If we have a previous replacement, the user must be explicitly
553 wrapping malloc/calloc/free. They better know what they're
554 doing... */
555 if (find_tm_replacement_function (from))
556 return;
558 str = IDENTIFIER_POINTER (DECL_NAME (from));
560 if (!strcmp (str, "malloc"))
561 to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
562 else if (!strcmp (str, "calloc"))
563 to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
564 else if (!strcmp (str, "free"))
565 to = builtin_decl_explicit (BUILT_IN_TM_FREE);
566 else
567 return;
569 TREE_NOTHROW (to) = 0;
571 record_tm_replacement (from, to);
574 /* Diagnostics for tm_safe functions/regions. Called by the front end
575 once we've lowered the function to high-gimple. */
577 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
578 Process exactly one statement. WI->INFO is set to non-null when in
579 the context of a tm_safe function, and null for a __transaction block. */
581 #define DIAG_TM_OUTER 1
582 #define DIAG_TM_SAFE 2
583 #define DIAG_TM_RELAXED 4
585 struct diagnose_tm
587 unsigned int summary_flags : 8;
588 unsigned int block_flags : 8;
589 unsigned int func_flags : 8;
590 unsigned int saw_volatile : 1;
591 gimple stmt;
594 /* Return true if T is a volatile variable of some kind. */
596 static bool
597 volatile_var_p (tree t)
599 return (SSA_VAR_P (t)
600 && TREE_THIS_VOLATILE (TREE_TYPE (t)));
603 /* Tree callback function for diagnose_tm pass. */
605 static tree
606 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
607 void *data)
609 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
610 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
612 if (volatile_var_p (*tp)
613 && d->block_flags & DIAG_TM_SAFE
614 && !d->saw_volatile)
616 d->saw_volatile = 1;
617 error_at (gimple_location (d->stmt),
618 "invalid volatile use of %qD inside transaction",
619 *tp);
622 return NULL_TREE;
625 static inline bool
626 is_tm_safe_or_pure (const_tree x)
628 return is_tm_safe (x) || is_tm_pure (x);
631 static tree
632 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
633 struct walk_stmt_info *wi)
635 gimple stmt = gsi_stmt (*gsi);
636 struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
638 /* Save stmt for use in leaf analysis. */
639 d->stmt = stmt;
641 switch (gimple_code (stmt))
643 case GIMPLE_CALL:
645 tree fn = gimple_call_fn (stmt);
647 if ((d->summary_flags & DIAG_TM_OUTER) == 0
648 && is_tm_may_cancel_outer (fn))
649 error_at (gimple_location (stmt),
650 "%<transaction_may_cancel_outer%> function call not within"
651 " outer transaction or %<transaction_may_cancel_outer%>");
653 if (d->summary_flags & DIAG_TM_SAFE)
655 bool is_safe, direct_call_p;
656 tree replacement;
658 if (TREE_CODE (fn) == ADDR_EXPR
659 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
661 direct_call_p = true;
662 replacement = TREE_OPERAND (fn, 0);
663 replacement = find_tm_replacement_function (replacement);
664 if (replacement)
665 fn = replacement;
667 else
669 direct_call_p = false;
670 replacement = NULL_TREE;
673 if (is_tm_safe_or_pure (fn))
674 is_safe = true;
675 else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
677 /* A function explicitly marked transaction_callable as
678 opposed to transaction_safe is being defined to be
679 unsafe as part of its ABI, regardless of its contents. */
680 is_safe = false;
682 else if (direct_call_p)
684 if (IS_TYPE_OR_DECL_P (fn)
685 && flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
686 is_safe = true;
687 else if (replacement)
689 /* ??? At present we've been considering replacements
690 merely transaction_callable, and therefore might
691 enter irrevocable. The tm_wrap attribute has not
692 yet made it into the new language spec. */
693 is_safe = false;
695 else
697 /* ??? Diagnostics for unmarked direct calls moved into
698 the IPA pass. Section 3.2 of the spec details how
699 functions not marked should be considered "implicitly
700 safe" based on having examined the function body. */
701 is_safe = true;
704 else
706 /* An unmarked indirect call. Consider it unsafe even
707 though optimization may yet figure out how to inline. */
708 is_safe = false;
711 if (!is_safe)
713 if (TREE_CODE (fn) == ADDR_EXPR)
714 fn = TREE_OPERAND (fn, 0);
715 if (d->block_flags & DIAG_TM_SAFE)
717 if (direct_call_p)
718 error_at (gimple_location (stmt),
719 "unsafe function call %qD within "
720 "atomic transaction", fn);
721 else
723 if (!DECL_P (fn) || DECL_NAME (fn))
724 error_at (gimple_location (stmt),
725 "unsafe function call %qE within "
726 "atomic transaction", fn);
727 else
728 error_at (gimple_location (stmt),
729 "unsafe indirect function call within "
730 "atomic transaction");
733 else
735 if (direct_call_p)
736 error_at (gimple_location (stmt),
737 "unsafe function call %qD within "
738 "%<transaction_safe%> function", fn);
739 else
741 if (!DECL_P (fn) || DECL_NAME (fn))
742 error_at (gimple_location (stmt),
743 "unsafe function call %qE within "
744 "%<transaction_safe%> function", fn);
745 else
746 error_at (gimple_location (stmt),
747 "unsafe indirect function call within "
748 "%<transaction_safe%> function");
754 break;
756 case GIMPLE_ASM:
757 /* ??? We ought to come up with a way to add attributes to
758 asm statements, and then add "transaction_safe" to it.
759 Either that or get the language spec to resurrect __tm_waiver. */
760 if (d->block_flags & DIAG_TM_SAFE)
761 error_at (gimple_location (stmt),
762 "asm not allowed in atomic transaction");
763 else if (d->func_flags & DIAG_TM_SAFE)
764 error_at (gimple_location (stmt),
765 "asm not allowed in %<transaction_safe%> function");
766 break;
768 case GIMPLE_TRANSACTION:
770 unsigned char inner_flags = DIAG_TM_SAFE;
772 if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
774 if (d->block_flags & DIAG_TM_SAFE)
775 error_at (gimple_location (stmt),
776 "relaxed transaction in atomic transaction");
777 else if (d->func_flags & DIAG_TM_SAFE)
778 error_at (gimple_location (stmt),
779 "relaxed transaction in %<transaction_safe%> function");
780 inner_flags = DIAG_TM_RELAXED;
782 else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
784 if (d->block_flags)
785 error_at (gimple_location (stmt),
786 "outer transaction in transaction");
787 else if (d->func_flags & DIAG_TM_OUTER)
788 error_at (gimple_location (stmt),
789 "outer transaction in "
790 "%<transaction_may_cancel_outer%> function");
791 else if (d->func_flags & DIAG_TM_SAFE)
792 error_at (gimple_location (stmt),
793 "outer transaction in %<transaction_safe%> function");
794 inner_flags |= DIAG_TM_OUTER;
797 *handled_ops_p = true;
798 if (gimple_transaction_body (stmt))
800 struct walk_stmt_info wi_inner;
801 struct diagnose_tm d_inner;
803 memset (&d_inner, 0, sizeof (d_inner));
804 d_inner.func_flags = d->func_flags;
805 d_inner.block_flags = d->block_flags | inner_flags;
806 d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
808 memset (&wi_inner, 0, sizeof (wi_inner));
809 wi_inner.info = &d_inner;
811 walk_gimple_seq (gimple_transaction_body (stmt),
812 diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
815 break;
817 default:
818 break;
821 return NULL_TREE;
824 static unsigned int
825 diagnose_tm_blocks (void)
827 struct walk_stmt_info wi;
828 struct diagnose_tm d;
830 memset (&d, 0, sizeof (d));
831 if (is_tm_may_cancel_outer (current_function_decl))
832 d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
833 else if (is_tm_safe (current_function_decl))
834 d.func_flags = DIAG_TM_SAFE;
835 d.summary_flags = d.func_flags;
837 memset (&wi, 0, sizeof (wi));
838 wi.info = &d;
840 walk_gimple_seq (gimple_body (current_function_decl),
841 diagnose_tm_1, diagnose_tm_1_op, &wi);
843 return 0;
846 namespace {
848 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 : 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 } // anon namespace
876 gimple_opt_pass *
877 make_pass_diagnose_tm_blocks (gcc::context *ctxt)
879 return new pass_diagnose_tm_blocks (ctxt);
882 /* Instead of instrumenting thread private memory, we save the
883 addresses in a log which we later use to save/restore the addresses
884 upon transaction start/restart.
886 The log is keyed by address, where each element contains individual
887 statements among different code paths that perform the store.
889 This log is later used to generate either plain save/restore of the
890 addresses upon transaction start/restart, or calls to the ITM_L*
891 logging functions.
893 So for something like:
895 struct large { int x[1000]; };
896 struct large lala = { 0 };
897 __transaction {
898 lala.x[i] = 123;
902 We can either save/restore:
904 lala = { 0 };
905 trxn = _ITM_startTransaction ();
906 if (trxn & a_saveLiveVariables)
907 tmp_lala1 = lala.x[i];
908 else if (a & a_restoreLiveVariables)
909 lala.x[i] = tmp_lala1;
911 or use the logging functions:
913 lala = { 0 };
914 trxn = _ITM_startTransaction ();
915 _ITM_LU4 (&lala.x[i]);
917 Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
918 far up the dominator tree to shadow all of the writes to a given
919 location (thus reducing the total number of logging calls), but not
920 so high as to be called on a path that does not perform a
921 write. */
923 /* One individual log entry. We may have multiple statements for the
924 same location if neither dominate each other (on different
925 execution paths). */
926 typedef struct tm_log_entry
928 /* Address to save. */
929 tree addr;
930 /* Entry block for the transaction this address occurs in. */
931 basic_block entry_block;
932 /* Dominating statements the store occurs in. */
933 gimple_vec stmts;
934 /* Initially, while we are building the log, we place a nonzero
935 value here to mean that this address *will* be saved with a
936 save/restore sequence. Later, when generating the save sequence
937 we place the SSA temp generated here. */
938 tree save_var;
939 } *tm_log_entry_t;
942 /* Log entry hashtable helpers. */
944 struct log_entry_hasher
946 typedef tm_log_entry value_type;
947 typedef tm_log_entry compare_type;
948 static inline hashval_t hash (const value_type *);
949 static inline bool equal (const value_type *, const compare_type *);
950 static inline void remove (value_type *);
953 /* Htab support. Return hash value for a `tm_log_entry'. */
954 inline hashval_t
955 log_entry_hasher::hash (const value_type *log)
957 return iterative_hash_expr (log->addr, 0);
960 /* Htab support. Return true if two log entries are the same. */
961 inline bool
962 log_entry_hasher::equal (const value_type *log1, const compare_type *log2)
964 /* FIXME:
966 rth: I suggest that we get rid of the component refs etc.
967 I.e. resolve the reference to base + offset.
969 We may need to actually finish a merge with mainline for this,
970 since we'd like to be presented with Richi's MEM_REF_EXPRs more
971 often than not. But in the meantime your tm_log_entry could save
972 the results of get_inner_reference.
974 See: g++.dg/tm/pr46653.C
977 /* Special case plain equality because operand_equal_p() below will
978 return FALSE if the addresses are equal but they have
979 side-effects (e.g. a volatile address). */
980 if (log1->addr == log2->addr)
981 return true;
983 return operand_equal_p (log1->addr, log2->addr, 0);
986 /* Htab support. Free one tm_log_entry. */
987 inline void
988 log_entry_hasher::remove (value_type *lp)
990 lp->stmts.release ();
991 free (lp);
995 /* The actual log. */
996 static hash_table<log_entry_hasher> *tm_log;
998 /* Addresses to log with a save/restore sequence. These should be in
999 dominator order. */
1000 static vec<tree> tm_log_save_addresses;
1002 enum thread_memory_type
1004 mem_non_local = 0,
1005 mem_thread_local,
1006 mem_transaction_local,
1007 mem_max
1010 typedef struct tm_new_mem_map
1012 /* SSA_NAME being dereferenced. */
1013 tree val;
1014 enum thread_memory_type local_new_memory;
1015 } tm_new_mem_map_t;
1017 /* Hashtable helpers. */
1019 struct tm_mem_map_hasher : typed_free_remove <tm_new_mem_map_t>
1021 typedef tm_new_mem_map_t value_type;
1022 typedef tm_new_mem_map_t compare_type;
1023 static inline hashval_t hash (const value_type *);
1024 static inline bool equal (const value_type *, const compare_type *);
1027 inline hashval_t
1028 tm_mem_map_hasher::hash (const value_type *v)
1030 return (intptr_t)v->val >> 4;
1033 inline bool
1034 tm_mem_map_hasher::equal (const value_type *v, const compare_type *c)
1036 return v->val == c->val;
1039 /* Map for an SSA_NAME originally pointing to a non aliased new piece
1040 of memory (malloc, alloc, etc). */
1041 static hash_table<tm_mem_map_hasher> *tm_new_mem_hash;
1043 /* Initialize logging data structures. */
1044 static void
1045 tm_log_init (void)
1047 tm_log = new hash_table<log_entry_hasher> (10);
1048 tm_new_mem_hash = new hash_table<tm_mem_map_hasher> (5);
1049 tm_log_save_addresses.create (5);
1052 /* Free logging data structures. */
1053 static void
1054 tm_log_delete (void)
1056 delete tm_log;
1057 tm_log = NULL;
1058 delete tm_new_mem_hash;
1059 tm_new_mem_hash = NULL;
1060 tm_log_save_addresses.release ();
1063 /* Return true if MEM is a transaction invariant memory for the TM
1064 region starting at REGION_ENTRY_BLOCK. */
1065 static bool
1066 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
1068 if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
1069 && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
1071 basic_block def_bb;
1073 def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
1074 return def_bb != region_entry_block
1075 && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
1078 mem = strip_invariant_refs (mem);
1079 return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
1082 /* Given an address ADDR in STMT, find it in the memory log or add it,
1083 making sure to keep only the addresses highest in the dominator
1084 tree.
1086 ENTRY_BLOCK is the entry_block for the transaction.
1088 If we find the address in the log, make sure it's either the same
1089 address, or an equivalent one that dominates ADDR.
1091 If we find the address, but neither ADDR dominates the found
1092 address, nor the found one dominates ADDR, we're on different
1093 execution paths. Add it.
1095 If known, ENTRY_BLOCK is the entry block for the region, otherwise
1096 NULL. */
1097 static void
1098 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
1100 tm_log_entry **slot;
1101 struct tm_log_entry l, *lp;
1103 l.addr = addr;
1104 slot = tm_log->find_slot (&l, INSERT);
1105 if (!*slot)
1107 tree type = TREE_TYPE (addr);
1109 lp = XNEW (struct tm_log_entry);
1110 lp->addr = addr;
1111 *slot = lp;
1113 /* Small invariant addresses can be handled as save/restores. */
1114 if (entry_block
1115 && transaction_invariant_address_p (lp->addr, entry_block)
1116 && TYPE_SIZE_UNIT (type) != NULL
1117 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type))
1118 && ((HOST_WIDE_INT) tree_to_uhwi (TYPE_SIZE_UNIT (type))
1119 < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1120 /* We must be able to copy this type normally. I.e., no
1121 special constructors and the like. */
1122 && !TREE_ADDRESSABLE (type))
1124 lp->save_var = create_tmp_reg (TREE_TYPE (lp->addr), "tm_save");
1125 lp->stmts.create (0);
1126 lp->entry_block = entry_block;
1127 /* Save addresses separately in dominator order so we don't
1128 get confused by overlapping addresses in the save/restore
1129 sequence. */
1130 tm_log_save_addresses.safe_push (lp->addr);
1132 else
1134 /* Use the logging functions. */
1135 lp->stmts.create (5);
1136 lp->stmts.quick_push (stmt);
1137 lp->save_var = NULL;
1140 else
1142 size_t i;
1143 gimple oldstmt;
1145 lp = *slot;
1147 /* If we're generating a save/restore sequence, we don't care
1148 about statements. */
1149 if (lp->save_var)
1150 return;
1152 for (i = 0; lp->stmts.iterate (i, &oldstmt); ++i)
1154 if (stmt == oldstmt)
1155 return;
1156 /* We already have a store to the same address, higher up the
1157 dominator tree. Nothing to do. */
1158 if (dominated_by_p (CDI_DOMINATORS,
1159 gimple_bb (stmt), gimple_bb (oldstmt)))
1160 return;
1161 /* We should be processing blocks in dominator tree order. */
1162 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1163 gimple_bb (oldstmt), gimple_bb (stmt)));
1165 /* Store is on a different code path. */
1166 lp->stmts.safe_push (stmt);
1170 /* Gimplify the address of a TARGET_MEM_REF. Return the SSA_NAME
1171 result, insert the new statements before GSI. */
1173 static tree
1174 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1176 if (TREE_CODE (x) == TARGET_MEM_REF)
1177 x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1178 else
1179 x = build_fold_addr_expr (x);
1180 return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1183 /* Instrument one address with the logging functions.
1184 ADDR is the address to save.
1185 STMT is the statement before which to place it. */
1186 static void
1187 tm_log_emit_stmt (tree addr, gimple stmt)
1189 tree type = TREE_TYPE (addr);
1190 tree size = TYPE_SIZE_UNIT (type);
1191 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1192 gimple log;
1193 enum built_in_function code = BUILT_IN_TM_LOG;
1195 if (type == float_type_node)
1196 code = BUILT_IN_TM_LOG_FLOAT;
1197 else if (type == double_type_node)
1198 code = BUILT_IN_TM_LOG_DOUBLE;
1199 else if (type == long_double_type_node)
1200 code = BUILT_IN_TM_LOG_LDOUBLE;
1201 else if (tree_fits_uhwi_p (size))
1203 unsigned int n = tree_to_uhwi (size);
1204 switch (n)
1206 case 1:
1207 code = BUILT_IN_TM_LOG_1;
1208 break;
1209 case 2:
1210 code = BUILT_IN_TM_LOG_2;
1211 break;
1212 case 4:
1213 code = BUILT_IN_TM_LOG_4;
1214 break;
1215 case 8:
1216 code = BUILT_IN_TM_LOG_8;
1217 break;
1218 default:
1219 code = BUILT_IN_TM_LOG;
1220 if (TREE_CODE (type) == VECTOR_TYPE)
1222 if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1223 code = BUILT_IN_TM_LOG_M64;
1224 else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1225 code = BUILT_IN_TM_LOG_M128;
1226 else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1227 code = BUILT_IN_TM_LOG_M256;
1229 break;
1233 addr = gimplify_addr (&gsi, addr);
1234 if (code == BUILT_IN_TM_LOG)
1235 log = gimple_build_call (builtin_decl_explicit (code), 2, addr, size);
1236 else
1237 log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1238 gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1241 /* Go through the log and instrument address that must be instrumented
1242 with the logging functions. Leave the save/restore addresses for
1243 later. */
1244 static void
1245 tm_log_emit (void)
1247 hash_table<log_entry_hasher>::iterator hi;
1248 struct tm_log_entry *lp;
1250 FOR_EACH_HASH_TABLE_ELEMENT (*tm_log, lp, tm_log_entry_t, hi)
1252 size_t i;
1253 gimple stmt;
1255 if (dump_file)
1257 fprintf (dump_file, "TM thread private mem logging: ");
1258 print_generic_expr (dump_file, lp->addr, 0);
1259 fprintf (dump_file, "\n");
1262 if (lp->save_var)
1264 if (dump_file)
1265 fprintf (dump_file, "DUMPING to variable\n");
1266 continue;
1268 else
1270 if (dump_file)
1271 fprintf (dump_file, "DUMPING with logging functions\n");
1272 for (i = 0; lp->stmts.iterate (i, &stmt); ++i)
1273 tm_log_emit_stmt (lp->addr, stmt);
1278 /* Emit the save sequence for the corresponding addresses in the log.
1279 ENTRY_BLOCK is the entry block for the transaction.
1280 BB is the basic block to insert the code in. */
1281 static void
1282 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1284 size_t i;
1285 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1286 gimple stmt;
1287 struct tm_log_entry l, *lp;
1289 for (i = 0; i < tm_log_save_addresses.length (); ++i)
1291 l.addr = tm_log_save_addresses[i];
1292 lp = *(tm_log->find_slot (&l, NO_INSERT));
1293 gcc_assert (lp->save_var != NULL);
1295 /* We only care about variables in the current transaction. */
1296 if (lp->entry_block != entry_block)
1297 continue;
1299 stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1301 /* Make sure we can create an SSA_NAME for this type. For
1302 instance, aggregates aren't allowed, in which case the system
1303 will create a VOP for us and everything will just work. */
1304 if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1306 lp->save_var = make_ssa_name (lp->save_var, stmt);
1307 gimple_assign_set_lhs (stmt, lp->save_var);
1310 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1314 /* Emit the restore sequence for the corresponding addresses in the log.
1315 ENTRY_BLOCK is the entry block for the transaction.
1316 BB is the basic block to insert the code in. */
1317 static void
1318 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1320 int i;
1321 struct tm_log_entry l, *lp;
1322 gimple_stmt_iterator gsi;
1323 gimple stmt;
1325 for (i = tm_log_save_addresses.length () - 1; i >= 0; i--)
1327 l.addr = tm_log_save_addresses[i];
1328 lp = *(tm_log->find_slot (&l, NO_INSERT));
1329 gcc_assert (lp->save_var != NULL);
1331 /* We only care about variables in the current transaction. */
1332 if (lp->entry_block != entry_block)
1333 continue;
1335 /* Restores are in LIFO order from the saves in case we have
1336 overlaps. */
1337 gsi = gsi_start_bb (bb);
1339 stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1340 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1345 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1346 struct walk_stmt_info *);
1347 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1348 struct walk_stmt_info *);
1350 /* Evaluate an address X being dereferenced and determine if it
1351 originally points to a non aliased new chunk of memory (malloc,
1352 alloca, etc).
1354 Return MEM_THREAD_LOCAL if it points to a thread-local address.
1355 Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1356 Return MEM_NON_LOCAL otherwise.
1358 ENTRY_BLOCK is the entry block to the transaction containing the
1359 dereference of X. */
1360 static enum thread_memory_type
1361 thread_private_new_memory (basic_block entry_block, tree x)
1363 gimple stmt = NULL;
1364 enum tree_code code;
1365 tm_new_mem_map_t **slot;
1366 tm_new_mem_map_t elt, *elt_p;
1367 tree val = x;
1368 enum thread_memory_type retval = mem_transaction_local;
1370 if (!entry_block
1371 || TREE_CODE (x) != SSA_NAME
1372 /* Possible uninitialized use, or a function argument. In
1373 either case, we don't care. */
1374 || SSA_NAME_IS_DEFAULT_DEF (x))
1375 return mem_non_local;
1377 /* Look in cache first. */
1378 elt.val = x;
1379 slot = tm_new_mem_hash->find_slot (&elt, INSERT);
1380 elt_p = *slot;
1381 if (elt_p)
1382 return elt_p->local_new_memory;
1384 /* Optimistically assume the memory is transaction local during
1385 processing. This catches recursion into this variable. */
1386 *slot = elt_p = XNEW (tm_new_mem_map_t);
1387 elt_p->val = val;
1388 elt_p->local_new_memory = mem_transaction_local;
1390 /* Search DEF chain to find the original definition of this address. */
1393 if (ptr_deref_may_alias_global_p (x))
1395 /* Address escapes. This is not thread-private. */
1396 retval = mem_non_local;
1397 goto new_memory_ret;
1400 stmt = SSA_NAME_DEF_STMT (x);
1402 /* If the malloc call is outside the transaction, this is
1403 thread-local. */
1404 if (retval != mem_thread_local
1405 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1406 retval = mem_thread_local;
1408 if (is_gimple_assign (stmt))
1410 code = gimple_assign_rhs_code (stmt);
1411 /* x = foo ==> foo */
1412 if (code == SSA_NAME)
1413 x = gimple_assign_rhs1 (stmt);
1414 /* x = foo + n ==> foo */
1415 else if (code == POINTER_PLUS_EXPR)
1416 x = gimple_assign_rhs1 (stmt);
1417 /* x = (cast*) foo ==> foo */
1418 else if (code == VIEW_CONVERT_EXPR || CONVERT_EXPR_CODE_P (code))
1419 x = gimple_assign_rhs1 (stmt);
1420 /* x = c ? op1 : op2 == > op1 or op2 just like a PHI */
1421 else if (code == COND_EXPR)
1423 tree op1 = gimple_assign_rhs2 (stmt);
1424 tree op2 = gimple_assign_rhs3 (stmt);
1425 enum thread_memory_type mem;
1426 retval = thread_private_new_memory (entry_block, op1);
1427 if (retval == mem_non_local)
1428 goto new_memory_ret;
1429 mem = thread_private_new_memory (entry_block, op2);
1430 retval = MIN (retval, mem);
1431 goto new_memory_ret;
1433 else
1435 retval = mem_non_local;
1436 goto new_memory_ret;
1439 else
1441 if (gimple_code (stmt) == GIMPLE_PHI)
1443 unsigned int i;
1444 enum thread_memory_type mem;
1445 tree phi_result = gimple_phi_result (stmt);
1447 /* If any of the ancestors are non-local, we are sure to
1448 be non-local. Otherwise we can avoid doing anything
1449 and inherit what has already been generated. */
1450 retval = mem_max;
1451 for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1453 tree op = PHI_ARG_DEF (stmt, i);
1455 /* Exclude self-assignment. */
1456 if (phi_result == op)
1457 continue;
1459 mem = thread_private_new_memory (entry_block, op);
1460 if (mem == mem_non_local)
1462 retval = mem;
1463 goto new_memory_ret;
1465 retval = MIN (retval, mem);
1467 goto new_memory_ret;
1469 break;
1472 while (TREE_CODE (x) == SSA_NAME);
1474 if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1475 /* Thread-local or transaction-local. */
1477 else
1478 retval = mem_non_local;
1480 new_memory_ret:
1481 elt_p->local_new_memory = retval;
1482 return retval;
1485 /* Determine whether X has to be instrumented using a read
1486 or write barrier.
1488 ENTRY_BLOCK is the entry block for the region where stmt resides
1489 in. NULL if unknown.
1491 STMT is the statement in which X occurs in. It is used for thread
1492 private memory instrumentation. If no TPM instrumentation is
1493 desired, STMT should be null. */
1494 static bool
1495 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1497 tree orig = x;
1498 while (handled_component_p (x))
1499 x = TREE_OPERAND (x, 0);
1501 switch (TREE_CODE (x))
1503 case INDIRECT_REF:
1504 case MEM_REF:
1506 enum thread_memory_type ret;
1508 ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1509 if (ret == mem_non_local)
1510 return true;
1511 if (stmt && ret == mem_thread_local)
1512 /* ?? Should we pass `orig', or the INDIRECT_REF X. ?? */
1513 tm_log_add (entry_block, orig, stmt);
1515 /* Transaction-locals require nothing at all. For malloc, a
1516 transaction restart frees the memory and we reallocate.
1517 For alloca, the stack pointer gets reset by the retry and
1518 we reallocate. */
1519 return false;
1522 case TARGET_MEM_REF:
1523 if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1524 return true;
1525 x = TREE_OPERAND (TMR_BASE (x), 0);
1526 if (TREE_CODE (x) == PARM_DECL)
1527 return false;
1528 gcc_assert (TREE_CODE (x) == VAR_DECL);
1529 /* FALLTHRU */
1531 case PARM_DECL:
1532 case RESULT_DECL:
1533 case VAR_DECL:
1534 if (DECL_BY_REFERENCE (x))
1536 /* ??? This value is a pointer, but aggregate_value_p has been
1537 jigged to return true which confuses needs_to_live_in_memory.
1538 This ought to be cleaned up generically.
1540 FIXME: Verify this still happens after the next mainline
1541 merge. Testcase ie g++.dg/tm/pr47554.C.
1543 return false;
1546 if (is_global_var (x))
1547 return !TREE_READONLY (x);
1548 if (/* FIXME: This condition should actually go below in the
1549 tm_log_add() call, however is_call_clobbered() depends on
1550 aliasing info which is not available during
1551 gimplification. Since requires_barrier() gets called
1552 during lower_sequence_tm/gimplification, leave the call
1553 to needs_to_live_in_memory until we eliminate
1554 lower_sequence_tm altogether. */
1555 needs_to_live_in_memory (x))
1556 return true;
1557 else
1559 /* For local memory that doesn't escape (aka thread private
1560 memory), we can either save the value at the beginning of
1561 the transaction and restore on restart, or call a tm
1562 function to dynamically save and restore on restart
1563 (ITM_L*). */
1564 if (stmt)
1565 tm_log_add (entry_block, orig, stmt);
1566 return false;
1569 default:
1570 return false;
1574 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1575 a transaction region. */
1577 static void
1578 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1580 gimple stmt = gsi_stmt (*gsi);
1582 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1583 *state |= GTMA_HAVE_LOAD;
1584 if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1585 *state |= GTMA_HAVE_STORE;
1588 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction. */
1590 static void
1591 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1593 gimple stmt = gsi_stmt (*gsi);
1594 tree fn;
1596 if (is_tm_pure_call (stmt))
1597 return;
1599 /* Check if this call is a transaction abort. */
1600 fn = gimple_call_fndecl (stmt);
1601 if (is_tm_abort (fn))
1602 *state |= GTMA_HAVE_ABORT;
1604 /* Note that something may happen. */
1605 *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1608 /* Lower a GIMPLE_TRANSACTION statement. */
1610 static void
1611 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1613 gimple g, stmt = gsi_stmt (*gsi);
1614 unsigned int *outer_state = (unsigned int *) wi->info;
1615 unsigned int this_state = 0;
1616 struct walk_stmt_info this_wi;
1618 /* First, lower the body. The scanning that we do inside gives
1619 us some idea of what we're dealing with. */
1620 memset (&this_wi, 0, sizeof (this_wi));
1621 this_wi.info = (void *) &this_state;
1622 walk_gimple_seq_mod (gimple_transaction_body_ptr (stmt),
1623 lower_sequence_tm, NULL, &this_wi);
1625 /* If there was absolutely nothing transaction related inside the
1626 transaction, we may elide it. Likewise if this is a nested
1627 transaction and does not contain an abort. */
1628 if (this_state == 0
1629 || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1631 if (outer_state)
1632 *outer_state |= this_state;
1634 gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1635 GSI_SAME_STMT);
1636 gimple_transaction_set_body (stmt, NULL);
1638 gsi_remove (gsi, true);
1639 wi->removed_stmt = true;
1640 return;
1643 /* Wrap the body of the transaction in a try-finally node so that
1644 the commit call is always properly called. */
1645 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1646 if (flag_exceptions)
1648 tree ptr;
1649 gimple_seq n_seq, e_seq;
1651 n_seq = gimple_seq_alloc_with_stmt (g);
1652 e_seq = NULL;
1654 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1655 1, integer_zero_node);
1656 ptr = create_tmp_var (ptr_type_node, NULL);
1657 gimple_call_set_lhs (g, ptr);
1658 gimple_seq_add_stmt (&e_seq, g);
1660 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1661 1, ptr);
1662 gimple_seq_add_stmt (&e_seq, g);
1664 g = gimple_build_eh_else (n_seq, e_seq);
1667 g = gimple_build_try (gimple_transaction_body (stmt),
1668 gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1669 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1671 gimple_transaction_set_body (stmt, NULL);
1673 /* If the transaction calls abort or if this is an outer transaction,
1674 add an "over" label afterwards. */
1675 if ((this_state & (GTMA_HAVE_ABORT))
1676 || (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER))
1678 tree label = create_artificial_label (UNKNOWN_LOCATION);
1679 gimple_transaction_set_label (stmt, label);
1680 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1683 /* Record the set of operations found for use later. */
1684 this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1685 gimple_transaction_set_subcode (stmt, this_state);
1688 /* Iterate through the statements in the sequence, lowering them all
1689 as appropriate for being in a transaction. */
1691 static tree
1692 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1693 struct walk_stmt_info *wi)
1695 unsigned int *state = (unsigned int *) wi->info;
1696 gimple stmt = gsi_stmt (*gsi);
1698 *handled_ops_p = true;
1699 switch (gimple_code (stmt))
1701 case GIMPLE_ASSIGN:
1702 /* Only memory reads/writes need to be instrumented. */
1703 if (gimple_assign_single_p (stmt))
1704 examine_assign_tm (state, gsi);
1705 break;
1707 case GIMPLE_CALL:
1708 examine_call_tm (state, gsi);
1709 break;
1711 case GIMPLE_ASM:
1712 *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1713 break;
1715 case GIMPLE_TRANSACTION:
1716 lower_transaction (gsi, wi);
1717 break;
1719 default:
1720 *handled_ops_p = !gimple_has_substatements (stmt);
1721 break;
1724 return NULL_TREE;
1727 /* Iterate through the statements in the sequence, lowering them all
1728 as appropriate for being outside of a transaction. */
1730 static tree
1731 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1732 struct walk_stmt_info * wi)
1734 gimple stmt = gsi_stmt (*gsi);
1736 if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1738 *handled_ops_p = true;
1739 lower_transaction (gsi, wi);
1741 else
1742 *handled_ops_p = !gimple_has_substatements (stmt);
1744 return NULL_TREE;
1747 /* Main entry point for flattening GIMPLE_TRANSACTION constructs. After
1748 this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1749 been moved out, and all the data required for constructing a proper
1750 CFG has been recorded. */
1752 static unsigned int
1753 execute_lower_tm (void)
1755 struct walk_stmt_info wi;
1756 gimple_seq body;
1758 /* Transactional clones aren't created until a later pass. */
1759 gcc_assert (!decl_is_tm_clone (current_function_decl));
1761 body = gimple_body (current_function_decl);
1762 memset (&wi, 0, sizeof (wi));
1763 walk_gimple_seq_mod (&body, lower_sequence_no_tm, NULL, &wi);
1764 gimple_set_body (current_function_decl, body);
1766 return 0;
1769 namespace {
1771 const pass_data pass_data_lower_tm =
1773 GIMPLE_PASS, /* type */
1774 "tmlower", /* name */
1775 OPTGROUP_NONE, /* optinfo_flags */
1776 TV_TRANS_MEM, /* tv_id */
1777 PROP_gimple_lcf, /* properties_required */
1778 0, /* properties_provided */
1779 0, /* properties_destroyed */
1780 0, /* todo_flags_start */
1781 0, /* todo_flags_finish */
1784 class pass_lower_tm : public gimple_opt_pass
1786 public:
1787 pass_lower_tm (gcc::context *ctxt)
1788 : gimple_opt_pass (pass_data_lower_tm, ctxt)
1791 /* opt_pass methods: */
1792 virtual bool gate (function *) { return flag_tm; }
1793 virtual unsigned int execute (function *) { return execute_lower_tm (); }
1795 }; // class pass_lower_tm
1797 } // anon namespace
1799 gimple_opt_pass *
1800 make_pass_lower_tm (gcc::context *ctxt)
1802 return new pass_lower_tm (ctxt);
1805 /* Collect region information for each transaction. */
1807 struct tm_region
1809 /* Link to the next unnested transaction. */
1810 struct tm_region *next;
1812 /* Link to the next inner transaction. */
1813 struct tm_region *inner;
1815 /* Link to the next outer transaction. */
1816 struct tm_region *outer;
1818 /* The GIMPLE_TRANSACTION statement beginning this transaction.
1819 After TM_MARK, this gets replaced by a call to
1820 BUILT_IN_TM_START. */
1821 gimple transaction_stmt;
1823 /* After TM_MARK expands the GIMPLE_TRANSACTION into a call to
1824 BUILT_IN_TM_START, this field is true if the transaction is an
1825 outer transaction. */
1826 bool original_transaction_was_outer;
1828 /* Return value from BUILT_IN_TM_START. */
1829 tree tm_state;
1831 /* The entry block to this region. This will always be the first
1832 block of the body of the transaction. */
1833 basic_block entry_block;
1835 /* The first block after an expanded call to _ITM_beginTransaction. */
1836 basic_block restart_block;
1838 /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1839 These blocks are still a part of the region (i.e., the border is
1840 inclusive). Note that this set is only complete for paths in the CFG
1841 starting at ENTRY_BLOCK, and that there is no exit block recorded for
1842 the edge to the "over" label. */
1843 bitmap exit_blocks;
1845 /* The set of all blocks that have an TM_IRREVOCABLE call. */
1846 bitmap irr_blocks;
1849 typedef struct tm_region *tm_region_p;
1851 /* True if there are pending edge statements to be committed for the
1852 current function being scanned in the tmmark pass. */
1853 bool pending_edge_inserts_p;
1855 static struct tm_region *all_tm_regions;
1856 static bitmap_obstack tm_obstack;
1859 /* A subroutine of tm_region_init. Record the existence of the
1860 GIMPLE_TRANSACTION statement in a tree of tm_region elements. */
1862 static struct tm_region *
1863 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1865 struct tm_region *region;
1867 region = (struct tm_region *)
1868 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1870 if (outer)
1872 region->next = outer->inner;
1873 outer->inner = region;
1875 else
1877 region->next = all_tm_regions;
1878 all_tm_regions = region;
1880 region->inner = NULL;
1881 region->outer = outer;
1883 region->transaction_stmt = stmt;
1884 region->original_transaction_was_outer = false;
1885 region->tm_state = NULL;
1887 /* There are either one or two edges out of the block containing
1888 the GIMPLE_TRANSACTION, one to the actual region and one to the
1889 "over" label if the region contains an abort. The former will
1890 always be the one marked FALLTHRU. */
1891 region->entry_block = FALLTHRU_EDGE (bb)->dest;
1893 region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1894 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1896 return region;
1899 /* A subroutine of tm_region_init. Record all the exit and
1900 irrevocable blocks in BB into the region's exit_blocks and
1901 irr_blocks bitmaps. Returns the new region being scanned. */
1903 static struct tm_region *
1904 tm_region_init_1 (struct tm_region *region, basic_block bb)
1906 gimple_stmt_iterator gsi;
1907 gimple g;
1909 if (!region
1910 || (!region->irr_blocks && !region->exit_blocks))
1911 return region;
1913 /* Check to see if this is the end of a region by seeing if it
1914 contains a call to __builtin_tm_commit{,_eh}. Note that the
1915 outermost region for DECL_IS_TM_CLONE need not collect this. */
1916 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1918 g = gsi_stmt (gsi);
1919 if (gimple_code (g) == GIMPLE_CALL)
1921 tree fn = gimple_call_fndecl (g);
1922 if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1924 if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1925 || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1926 && region->exit_blocks)
1928 bitmap_set_bit (region->exit_blocks, bb->index);
1929 region = region->outer;
1930 break;
1932 if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1933 bitmap_set_bit (region->irr_blocks, bb->index);
1937 return region;
1940 /* Collect all of the transaction regions within the current function
1941 and record them in ALL_TM_REGIONS. The REGION parameter may specify
1942 an "outermost" region for use by tm clones. */
1944 static void
1945 tm_region_init (struct tm_region *region)
1947 gimple g;
1948 edge_iterator ei;
1949 edge e;
1950 basic_block bb;
1951 auto_vec<basic_block> queue;
1952 bitmap visited_blocks = BITMAP_ALLOC (NULL);
1953 struct tm_region *old_region;
1954 auto_vec<tm_region_p> bb_regions;
1956 all_tm_regions = region;
1957 bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1959 /* We could store this information in bb->aux, but we may get called
1960 through get_all_tm_blocks() from another pass that may be already
1961 using bb->aux. */
1962 bb_regions.safe_grow_cleared (last_basic_block_for_fn (cfun));
1964 queue.safe_push (bb);
1965 bb_regions[bb->index] = region;
1968 bb = queue.pop ();
1969 region = bb_regions[bb->index];
1970 bb_regions[bb->index] = NULL;
1972 /* Record exit and irrevocable blocks. */
1973 region = tm_region_init_1 (region, bb);
1975 /* Check for the last statement in the block beginning a new region. */
1976 g = last_stmt (bb);
1977 old_region = region;
1978 if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1979 region = tm_region_init_0 (region, bb, g);
1981 /* Process subsequent blocks. */
1982 FOR_EACH_EDGE (e, ei, bb->succs)
1983 if (!bitmap_bit_p (visited_blocks, e->dest->index))
1985 bitmap_set_bit (visited_blocks, e->dest->index);
1986 queue.safe_push (e->dest);
1988 /* If the current block started a new region, make sure that only
1989 the entry block of the new region is associated with this region.
1990 Other successors are still part of the old region. */
1991 if (old_region != region && e->dest != region->entry_block)
1992 bb_regions[e->dest->index] = old_region;
1993 else
1994 bb_regions[e->dest->index] = region;
1997 while (!queue.is_empty ());
1998 BITMAP_FREE (visited_blocks);
2001 /* The "gate" function for all transactional memory expansion and optimization
2002 passes. We collect region information for each top-level transaction, and
2003 if we don't find any, we skip all of the TM passes. Each region will have
2004 all of the exit blocks recorded, and the originating statement. */
2006 static bool
2007 gate_tm_init (void)
2009 if (!flag_tm)
2010 return false;
2012 calculate_dominance_info (CDI_DOMINATORS);
2013 bitmap_obstack_initialize (&tm_obstack);
2015 /* If the function is a TM_CLONE, then the entire function is the region. */
2016 if (decl_is_tm_clone (current_function_decl))
2018 struct tm_region *region = (struct tm_region *)
2019 obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
2020 memset (region, 0, sizeof (*region));
2021 region->entry_block = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
2022 /* For a clone, the entire function is the region. But even if
2023 we don't need to record any exit blocks, we may need to
2024 record irrevocable blocks. */
2025 region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
2027 tm_region_init (region);
2029 else
2031 tm_region_init (NULL);
2033 /* If we didn't find any regions, cleanup and skip the whole tree
2034 of tm-related optimizations. */
2035 if (all_tm_regions == NULL)
2037 bitmap_obstack_release (&tm_obstack);
2038 return false;
2042 return true;
2045 namespace {
2047 const pass_data pass_data_tm_init =
2049 GIMPLE_PASS, /* type */
2050 "*tminit", /* name */
2051 OPTGROUP_NONE, /* optinfo_flags */
2052 TV_TRANS_MEM, /* tv_id */
2053 ( PROP_ssa | PROP_cfg ), /* properties_required */
2054 0, /* properties_provided */
2055 0, /* properties_destroyed */
2056 0, /* todo_flags_start */
2057 0, /* todo_flags_finish */
2060 class pass_tm_init : public gimple_opt_pass
2062 public:
2063 pass_tm_init (gcc::context *ctxt)
2064 : gimple_opt_pass (pass_data_tm_init, ctxt)
2067 /* opt_pass methods: */
2068 virtual bool gate (function *) { return gate_tm_init (); }
2070 }; // class pass_tm_init
2072 } // anon namespace
2074 gimple_opt_pass *
2075 make_pass_tm_init (gcc::context *ctxt)
2077 return new pass_tm_init (ctxt);
2080 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
2081 represented by STATE. */
2083 static inline void
2084 transaction_subcode_ior (struct tm_region *region, unsigned flags)
2086 if (region && region->transaction_stmt)
2088 flags |= gimple_transaction_subcode (region->transaction_stmt);
2089 gimple_transaction_set_subcode (region->transaction_stmt, flags);
2093 /* Construct a memory load in a transactional context. Return the
2094 gimple statement performing the load, or NULL if there is no
2095 TM_LOAD builtin of the appropriate size to do the load.
2097 LOC is the location to use for the new statement(s). */
2099 static gimple
2100 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2102 enum built_in_function code = END_BUILTINS;
2103 tree t, type = TREE_TYPE (rhs), decl;
2104 gimple gcall;
2106 if (type == float_type_node)
2107 code = BUILT_IN_TM_LOAD_FLOAT;
2108 else if (type == double_type_node)
2109 code = BUILT_IN_TM_LOAD_DOUBLE;
2110 else if (type == long_double_type_node)
2111 code = BUILT_IN_TM_LOAD_LDOUBLE;
2112 else if (TYPE_SIZE_UNIT (type) != NULL
2113 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2115 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2117 case 1:
2118 code = BUILT_IN_TM_LOAD_1;
2119 break;
2120 case 2:
2121 code = BUILT_IN_TM_LOAD_2;
2122 break;
2123 case 4:
2124 code = BUILT_IN_TM_LOAD_4;
2125 break;
2126 case 8:
2127 code = BUILT_IN_TM_LOAD_8;
2128 break;
2132 if (code == END_BUILTINS)
2134 decl = targetm.vectorize.builtin_tm_load (type);
2135 if (!decl)
2136 return NULL;
2138 else
2139 decl = builtin_decl_explicit (code);
2141 t = gimplify_addr (gsi, rhs);
2142 gcall = gimple_build_call (decl, 1, t);
2143 gimple_set_location (gcall, loc);
2145 t = TREE_TYPE (TREE_TYPE (decl));
2146 if (useless_type_conversion_p (type, t))
2148 gimple_call_set_lhs (gcall, lhs);
2149 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2151 else
2153 gimple g;
2154 tree temp;
2156 temp = create_tmp_reg (t, NULL);
2157 gimple_call_set_lhs (gcall, temp);
2158 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2160 t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2161 g = gimple_build_assign (lhs, t);
2162 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2165 return gcall;
2169 /* Similarly for storing TYPE in a transactional context. */
2171 static gimple
2172 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2174 enum built_in_function code = END_BUILTINS;
2175 tree t, fn, type = TREE_TYPE (rhs), simple_type;
2176 gimple gcall;
2178 if (type == float_type_node)
2179 code = BUILT_IN_TM_STORE_FLOAT;
2180 else if (type == double_type_node)
2181 code = BUILT_IN_TM_STORE_DOUBLE;
2182 else if (type == long_double_type_node)
2183 code = BUILT_IN_TM_STORE_LDOUBLE;
2184 else if (TYPE_SIZE_UNIT (type) != NULL
2185 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2187 switch (tree_to_uhwi (TYPE_SIZE_UNIT (type)))
2189 case 1:
2190 code = BUILT_IN_TM_STORE_1;
2191 break;
2192 case 2:
2193 code = BUILT_IN_TM_STORE_2;
2194 break;
2195 case 4:
2196 code = BUILT_IN_TM_STORE_4;
2197 break;
2198 case 8:
2199 code = BUILT_IN_TM_STORE_8;
2200 break;
2204 if (code == END_BUILTINS)
2206 fn = targetm.vectorize.builtin_tm_store (type);
2207 if (!fn)
2208 return NULL;
2210 else
2211 fn = builtin_decl_explicit (code);
2213 simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2215 if (TREE_CODE (rhs) == CONSTRUCTOR)
2217 /* Handle the easy initialization to zero. */
2218 if (!CONSTRUCTOR_ELTS (rhs))
2219 rhs = build_int_cst (simple_type, 0);
2220 else
2222 /* ...otherwise punt to the caller and probably use
2223 BUILT_IN_TM_MEMMOVE, because we can't wrap a
2224 VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2225 valid gimple. */
2226 return NULL;
2229 else if (!useless_type_conversion_p (simple_type, type))
2231 gimple g;
2232 tree temp;
2234 temp = create_tmp_reg (simple_type, NULL);
2235 t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2236 g = gimple_build_assign (temp, t);
2237 gimple_set_location (g, loc);
2238 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2240 rhs = temp;
2243 t = gimplify_addr (gsi, lhs);
2244 gcall = gimple_build_call (fn, 2, t, rhs);
2245 gimple_set_location (gcall, loc);
2246 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2248 return gcall;
2252 /* Expand an assignment statement into transactional builtins. */
2254 static void
2255 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2257 gimple stmt = gsi_stmt (*gsi);
2258 location_t loc = gimple_location (stmt);
2259 tree lhs = gimple_assign_lhs (stmt);
2260 tree rhs = gimple_assign_rhs1 (stmt);
2261 bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2262 bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2263 gimple gcall = NULL;
2265 if (!load_p && !store_p)
2267 /* Add thread private addresses to log if applicable. */
2268 requires_barrier (region->entry_block, lhs, stmt);
2269 gsi_next (gsi);
2270 return;
2273 // Remove original load/store statement.
2274 gsi_remove (gsi, true);
2276 if (load_p && !store_p)
2278 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2279 gcall = build_tm_load (loc, lhs, rhs, gsi);
2281 else if (store_p && !load_p)
2283 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2284 gcall = build_tm_store (loc, lhs, rhs, gsi);
2286 if (!gcall)
2288 tree lhs_addr, rhs_addr, tmp;
2290 if (load_p)
2291 transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2292 if (store_p)
2293 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2295 /* ??? Figure out if there's any possible overlap between the LHS
2296 and the RHS and if not, use MEMCPY. */
2298 if (load_p && is_gimple_reg (lhs))
2300 tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2301 lhs_addr = build_fold_addr_expr (tmp);
2303 else
2305 tmp = NULL_TREE;
2306 lhs_addr = gimplify_addr (gsi, lhs);
2308 rhs_addr = gimplify_addr (gsi, rhs);
2309 gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2310 3, lhs_addr, rhs_addr,
2311 TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2312 gimple_set_location (gcall, loc);
2313 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2315 if (tmp)
2317 gcall = gimple_build_assign (lhs, tmp);
2318 gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2322 /* Now that we have the load/store in its instrumented form, add
2323 thread private addresses to the log if applicable. */
2324 if (!store_p)
2325 requires_barrier (region->entry_block, lhs, gcall);
2327 // The calls to build_tm_{store,load} above inserted the instrumented
2328 // call into the stream.
2329 // gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2333 /* Expand a call statement as appropriate for a transaction. That is,
2334 either verify that the call does not affect the transaction, or
2335 redirect the call to a clone that handles transactions, or change
2336 the transaction state to IRREVOCABLE. Return true if the call is
2337 one of the builtins that end a transaction. */
2339 static bool
2340 expand_call_tm (struct tm_region *region,
2341 gimple_stmt_iterator *gsi)
2343 gimple stmt = gsi_stmt (*gsi);
2344 tree lhs = gimple_call_lhs (stmt);
2345 tree fn_decl;
2346 struct cgraph_node *node;
2347 bool retval = false;
2349 fn_decl = gimple_call_fndecl (stmt);
2351 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2352 || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2353 transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2354 if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2355 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2357 if (is_tm_pure_call (stmt))
2358 return false;
2360 if (fn_decl)
2361 retval = is_tm_ending_fndecl (fn_decl);
2362 if (!retval)
2364 /* Assume all non-const/pure calls write to memory, except
2365 transaction ending builtins. */
2366 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2369 /* For indirect calls, we already generated a call into the runtime. */
2370 if (!fn_decl)
2372 tree fn = gimple_call_fn (stmt);
2374 /* We are guaranteed never to go irrevocable on a safe or pure
2375 call, and the pure call was handled above. */
2376 if (is_tm_safe (fn))
2377 return false;
2378 else
2379 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2381 return false;
2384 node = cgraph_node::get (fn_decl);
2385 /* All calls should have cgraph here. */
2386 if (!node)
2388 /* We can have a nodeless call here if some pass after IPA-tm
2389 added uninstrumented calls. For example, loop distribution
2390 can transform certain loop constructs into __builtin_mem*
2391 calls. In this case, see if we have a suitable TM
2392 replacement and fill in the gaps. */
2393 gcc_assert (DECL_BUILT_IN_CLASS (fn_decl) == BUILT_IN_NORMAL);
2394 enum built_in_function code = DECL_FUNCTION_CODE (fn_decl);
2395 gcc_assert (code == BUILT_IN_MEMCPY
2396 || code == BUILT_IN_MEMMOVE
2397 || code == BUILT_IN_MEMSET);
2399 tree repl = find_tm_replacement_function (fn_decl);
2400 if (repl)
2402 gimple_call_set_fndecl (stmt, repl);
2403 update_stmt (stmt);
2404 node = cgraph_node::create (repl);
2405 node->local.tm_may_enter_irr = false;
2406 return expand_call_tm (region, gsi);
2408 gcc_unreachable ();
2410 if (node->local.tm_may_enter_irr)
2411 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2413 if (is_tm_abort (fn_decl))
2415 transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2416 return true;
2419 /* Instrument the store if needed.
2421 If the assignment happens inside the function call (return slot
2422 optimization), there is no instrumentation to be done, since
2423 the callee should have done the right thing. */
2424 if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2425 && !gimple_call_return_slot_opt_p (stmt))
2427 tree tmp = create_tmp_reg (TREE_TYPE (lhs), NULL);
2428 location_t loc = gimple_location (stmt);
2429 edge fallthru_edge = NULL;
2431 /* Remember if the call was going to throw. */
2432 if (stmt_can_throw_internal (stmt))
2434 edge_iterator ei;
2435 edge e;
2436 basic_block bb = gimple_bb (stmt);
2438 FOR_EACH_EDGE (e, ei, bb->succs)
2439 if (e->flags & EDGE_FALLTHRU)
2441 fallthru_edge = e;
2442 break;
2446 gimple_call_set_lhs (stmt, tmp);
2447 update_stmt (stmt);
2448 stmt = gimple_build_assign (lhs, tmp);
2449 gimple_set_location (stmt, loc);
2451 /* We cannot throw in the middle of a BB. If the call was going
2452 to throw, place the instrumentation on the fallthru edge, so
2453 the call remains the last statement in the block. */
2454 if (fallthru_edge)
2456 gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2457 gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2458 expand_assign_tm (region, &fallthru_gsi);
2459 gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2460 pending_edge_inserts_p = true;
2462 else
2464 gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2465 expand_assign_tm (region, gsi);
2468 transaction_subcode_ior (region, GTMA_HAVE_STORE);
2471 return retval;
2475 /* Expand all statements in BB as appropriate for being inside
2476 a transaction. */
2478 static void
2479 expand_block_tm (struct tm_region *region, basic_block bb)
2481 gimple_stmt_iterator gsi;
2483 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2485 gimple stmt = gsi_stmt (gsi);
2486 switch (gimple_code (stmt))
2488 case GIMPLE_ASSIGN:
2489 /* Only memory reads/writes need to be instrumented. */
2490 if (gimple_assign_single_p (stmt)
2491 && !gimple_clobber_p (stmt))
2493 expand_assign_tm (region, &gsi);
2494 continue;
2496 break;
2498 case GIMPLE_CALL:
2499 if (expand_call_tm (region, &gsi))
2500 return;
2501 break;
2503 case GIMPLE_ASM:
2504 gcc_unreachable ();
2506 default:
2507 break;
2509 if (!gsi_end_p (gsi))
2510 gsi_next (&gsi);
2514 /* Return the list of basic-blocks in REGION.
2516 STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2517 following a TM_IRREVOCABLE call.
2519 INCLUDE_UNINSTRUMENTED_P is TRUE if we should include the
2520 uninstrumented code path blocks in the list of basic blocks
2521 returned, false otherwise. */
2523 static vec<basic_block>
2524 get_tm_region_blocks (basic_block entry_block,
2525 bitmap exit_blocks,
2526 bitmap irr_blocks,
2527 bitmap all_region_blocks,
2528 bool stop_at_irrevocable_p,
2529 bool include_uninstrumented_p = true)
2531 vec<basic_block> bbs = vNULL;
2532 unsigned i;
2533 edge e;
2534 edge_iterator ei;
2535 bitmap visited_blocks = BITMAP_ALLOC (NULL);
2537 i = 0;
2538 bbs.safe_push (entry_block);
2539 bitmap_set_bit (visited_blocks, entry_block->index);
2543 basic_block bb = bbs[i++];
2545 if (exit_blocks &&
2546 bitmap_bit_p (exit_blocks, bb->index))
2547 continue;
2549 if (stop_at_irrevocable_p
2550 && irr_blocks
2551 && bitmap_bit_p (irr_blocks, bb->index))
2552 continue;
2554 FOR_EACH_EDGE (e, ei, bb->succs)
2555 if ((include_uninstrumented_p
2556 || !(e->flags & EDGE_TM_UNINSTRUMENTED))
2557 && !bitmap_bit_p (visited_blocks, e->dest->index))
2559 bitmap_set_bit (visited_blocks, e->dest->index);
2560 bbs.safe_push (e->dest);
2563 while (i < bbs.length ());
2565 if (all_region_blocks)
2566 bitmap_ior_into (all_region_blocks, visited_blocks);
2568 BITMAP_FREE (visited_blocks);
2569 return bbs;
2572 // Callback data for collect_bb2reg.
2573 struct bb2reg_stuff
2575 vec<tm_region_p> *bb2reg;
2576 bool include_uninstrumented_p;
2579 // Callback for expand_regions, collect innermost region data for each bb.
2580 static void *
2581 collect_bb2reg (struct tm_region *region, void *data)
2583 struct bb2reg_stuff *stuff = (struct bb2reg_stuff *)data;
2584 vec<tm_region_p> *bb2reg = stuff->bb2reg;
2585 vec<basic_block> queue;
2586 unsigned int i;
2587 basic_block bb;
2589 queue = get_tm_region_blocks (region->entry_block,
2590 region->exit_blocks,
2591 region->irr_blocks,
2592 NULL,
2593 /*stop_at_irr_p=*/true,
2594 stuff->include_uninstrumented_p);
2596 // We expect expand_region to perform a post-order traversal of the region
2597 // tree. Therefore the last region seen for any bb is the innermost.
2598 FOR_EACH_VEC_ELT (queue, i, bb)
2599 (*bb2reg)[bb->index] = region;
2601 queue.release ();
2602 return NULL;
2605 // Returns a vector, indexed by BB->INDEX, of the innermost tm_region to
2606 // which a basic block belongs. Note that we only consider the instrumented
2607 // code paths for the region; the uninstrumented code paths are ignored if
2608 // INCLUDE_UNINSTRUMENTED_P is false.
2610 // ??? This data is very similar to the bb_regions array that is collected
2611 // during tm_region_init. Or, rather, this data is similar to what could
2612 // be used within tm_region_init. The actual computation in tm_region_init
2613 // begins and ends with bb_regions entirely full of NULL pointers, due to
2614 // the way in which pointers are swapped in and out of the array.
2616 // ??? Our callers expect that blocks are not shared between transactions.
2617 // When the optimizers get too smart, and blocks are shared, then during
2618 // the tm_mark phase we'll add log entries to only one of the two transactions,
2619 // and in the tm_edge phase we'll add edges to the CFG that create invalid
2620 // cycles. The symptom being SSA defs that do not dominate their uses.
2621 // Note that the optimizers were locally correct with their transformation,
2622 // as we have no info within the program that suggests that the blocks cannot
2623 // be shared.
2625 // ??? There is currently a hack inside tree-ssa-pre.c to work around the
2626 // only known instance of this block sharing.
2628 static vec<tm_region_p>
2629 get_bb_regions_instrumented (bool traverse_clones,
2630 bool include_uninstrumented_p)
2632 unsigned n = last_basic_block_for_fn (cfun);
2633 struct bb2reg_stuff stuff;
2634 vec<tm_region_p> ret;
2636 ret.create (n);
2637 ret.safe_grow_cleared (n);
2638 stuff.bb2reg = &ret;
2639 stuff.include_uninstrumented_p = include_uninstrumented_p;
2640 expand_regions (all_tm_regions, collect_bb2reg, &stuff, traverse_clones);
2642 return ret;
2645 /* Set the IN_TRANSACTION for all gimple statements that appear in a
2646 transaction. */
2648 void
2649 compute_transaction_bits (void)
2651 struct tm_region *region;
2652 vec<basic_block> queue;
2653 unsigned int i;
2654 basic_block bb;
2656 /* ?? Perhaps we need to abstract gate_tm_init further, because we
2657 certainly don't need it to calculate CDI_DOMINATOR info. */
2658 gate_tm_init ();
2660 FOR_EACH_BB_FN (bb, cfun)
2661 bb->flags &= ~BB_IN_TRANSACTION;
2663 for (region = all_tm_regions; region; region = region->next)
2665 queue = get_tm_region_blocks (region->entry_block,
2666 region->exit_blocks,
2667 region->irr_blocks,
2668 NULL,
2669 /*stop_at_irr_p=*/true);
2670 for (i = 0; queue.iterate (i, &bb); ++i)
2671 bb->flags |= BB_IN_TRANSACTION;
2672 queue.release ();
2675 if (all_tm_regions)
2676 bitmap_obstack_release (&tm_obstack);
2679 /* Replace the GIMPLE_TRANSACTION in this region with the corresponding
2680 call to BUILT_IN_TM_START. */
2682 static void *
2683 expand_transaction (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2685 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2686 basic_block transaction_bb = gimple_bb (region->transaction_stmt);
2687 tree tm_state = region->tm_state;
2688 tree tm_state_type = TREE_TYPE (tm_state);
2689 edge abort_edge = NULL;
2690 edge inst_edge = NULL;
2691 edge uninst_edge = NULL;
2692 edge fallthru_edge = NULL;
2694 // Identify the various successors of the transaction start.
2696 edge_iterator i;
2697 edge e;
2698 FOR_EACH_EDGE (e, i, transaction_bb->succs)
2700 if (e->flags & EDGE_TM_ABORT)
2701 abort_edge = e;
2702 else if (e->flags & EDGE_TM_UNINSTRUMENTED)
2703 uninst_edge = e;
2704 else
2705 inst_edge = e;
2706 if (e->flags & EDGE_FALLTHRU)
2707 fallthru_edge = e;
2711 /* ??? There are plenty of bits here we're not computing. */
2713 int subcode = gimple_transaction_subcode (region->transaction_stmt);
2714 int flags = 0;
2715 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2716 flags |= PR_DOESGOIRREVOCABLE;
2717 if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2718 flags |= PR_HASNOIRREVOCABLE;
2719 /* If the transaction does not have an abort in lexical scope and is not
2720 marked as an outer transaction, then it will never abort. */
2721 if ((subcode & GTMA_HAVE_ABORT) == 0 && (subcode & GTMA_IS_OUTER) == 0)
2722 flags |= PR_HASNOABORT;
2723 if ((subcode & GTMA_HAVE_STORE) == 0)
2724 flags |= PR_READONLY;
2725 if (inst_edge && !(subcode & GTMA_HAS_NO_INSTRUMENTATION))
2726 flags |= PR_INSTRUMENTEDCODE;
2727 if (uninst_edge)
2728 flags |= PR_UNINSTRUMENTEDCODE;
2729 if (subcode & GTMA_IS_OUTER)
2730 region->original_transaction_was_outer = true;
2731 tree t = build_int_cst (tm_state_type, flags);
2732 gimple call = gimple_build_call (tm_start, 1, t);
2733 gimple_call_set_lhs (call, tm_state);
2734 gimple_set_location (call, gimple_location (region->transaction_stmt));
2736 // Replace the GIMPLE_TRANSACTION with the call to BUILT_IN_TM_START.
2737 gimple_stmt_iterator gsi = gsi_last_bb (transaction_bb);
2738 gcc_assert (gsi_stmt (gsi) == region->transaction_stmt);
2739 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
2740 gsi_remove (&gsi, true);
2741 region->transaction_stmt = call;
2744 // Generate log saves.
2745 if (!tm_log_save_addresses.is_empty ())
2746 tm_log_emit_saves (region->entry_block, transaction_bb);
2748 // In the beginning, we've no tests to perform on transaction restart.
2749 // Note that after this point, transaction_bb becomes the "most recent
2750 // block containing tests for the transaction".
2751 region->restart_block = region->entry_block;
2753 // Generate log restores.
2754 if (!tm_log_save_addresses.is_empty ())
2756 basic_block test_bb = create_empty_bb (transaction_bb);
2757 basic_block code_bb = create_empty_bb (test_bb);
2758 basic_block join_bb = create_empty_bb (code_bb);
2759 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2760 add_bb_to_loop (code_bb, transaction_bb->loop_father);
2761 add_bb_to_loop (join_bb, transaction_bb->loop_father);
2762 if (region->restart_block == region->entry_block)
2763 region->restart_block = test_bb;
2765 tree t1 = create_tmp_reg (tm_state_type, NULL);
2766 tree t2 = build_int_cst (tm_state_type, A_RESTORELIVEVARIABLES);
2767 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2768 tm_state, t2);
2769 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2770 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2772 t2 = build_int_cst (tm_state_type, 0);
2773 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2774 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2776 tm_log_emit_restores (region->entry_block, code_bb);
2778 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2779 edge et = make_edge (test_bb, code_bb, EDGE_TRUE_VALUE);
2780 edge ef = make_edge (test_bb, join_bb, EDGE_FALSE_VALUE);
2781 redirect_edge_pred (fallthru_edge, join_bb);
2783 join_bb->frequency = test_bb->frequency = transaction_bb->frequency;
2784 join_bb->count = test_bb->count = transaction_bb->count;
2786 ei->probability = PROB_ALWAYS;
2787 et->probability = PROB_LIKELY;
2788 ef->probability = PROB_UNLIKELY;
2789 et->count = apply_probability (test_bb->count, et->probability);
2790 ef->count = apply_probability (test_bb->count, ef->probability);
2792 code_bb->count = et->count;
2793 code_bb->frequency = EDGE_FREQUENCY (et);
2795 transaction_bb = join_bb;
2798 // If we have an ABORT edge, create a test to perform the abort.
2799 if (abort_edge)
2801 basic_block test_bb = create_empty_bb (transaction_bb);
2802 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2803 if (region->restart_block == region->entry_block)
2804 region->restart_block = test_bb;
2806 tree t1 = create_tmp_reg (tm_state_type, NULL);
2807 tree t2 = build_int_cst (tm_state_type, A_ABORTTRANSACTION);
2808 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2809 tm_state, t2);
2810 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2811 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2813 t2 = build_int_cst (tm_state_type, 0);
2814 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2815 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2817 edge ei = make_edge (transaction_bb, test_bb, EDGE_FALLTHRU);
2818 test_bb->frequency = transaction_bb->frequency;
2819 test_bb->count = transaction_bb->count;
2820 ei->probability = PROB_ALWAYS;
2822 // Not abort edge. If both are live, chose one at random as we'll
2823 // we'll be fixing that up below.
2824 redirect_edge_pred (fallthru_edge, test_bb);
2825 fallthru_edge->flags = EDGE_FALSE_VALUE;
2826 fallthru_edge->probability = PROB_VERY_LIKELY;
2827 fallthru_edge->count
2828 = apply_probability (test_bb->count, fallthru_edge->probability);
2830 // Abort/over edge.
2831 redirect_edge_pred (abort_edge, test_bb);
2832 abort_edge->flags = EDGE_TRUE_VALUE;
2833 abort_edge->probability = PROB_VERY_UNLIKELY;
2834 abort_edge->count
2835 = apply_probability (test_bb->count, abort_edge->probability);
2837 transaction_bb = test_bb;
2840 // If we have both instrumented and uninstrumented code paths, select one.
2841 if (inst_edge && uninst_edge)
2843 basic_block test_bb = create_empty_bb (transaction_bb);
2844 add_bb_to_loop (test_bb, transaction_bb->loop_father);
2845 if (region->restart_block == region->entry_block)
2846 region->restart_block = test_bb;
2848 tree t1 = create_tmp_reg (tm_state_type, NULL);
2849 tree t2 = build_int_cst (tm_state_type, A_RUNUNINSTRUMENTEDCODE);
2851 gimple stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1,
2852 tm_state, t2);
2853 gimple_stmt_iterator gsi = gsi_last_bb (test_bb);
2854 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2856 t2 = build_int_cst (tm_state_type, 0);
2857 stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2858 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
2860 // Create the edge into test_bb first, as we want to copy values
2861 // out of the fallthru edge.
2862 edge e = make_edge (transaction_bb, test_bb, fallthru_edge->flags);
2863 e->probability = fallthru_edge->probability;
2864 test_bb->count = e->count = fallthru_edge->count;
2865 test_bb->frequency = EDGE_FREQUENCY (e);
2867 // Now update the edges to the inst/uninist implementations.
2868 // For now assume that the paths are equally likely. When using HTM,
2869 // we'll try the uninst path first and fallback to inst path if htm
2870 // buffers are exceeded. Without HTM we start with the inst path and
2871 // use the uninst path when falling back to serial mode.
2872 redirect_edge_pred (inst_edge, test_bb);
2873 inst_edge->flags = EDGE_FALSE_VALUE;
2874 inst_edge->probability = REG_BR_PROB_BASE / 2;
2875 inst_edge->count
2876 = apply_probability (test_bb->count, inst_edge->probability);
2878 redirect_edge_pred (uninst_edge, test_bb);
2879 uninst_edge->flags = EDGE_TRUE_VALUE;
2880 uninst_edge->probability = REG_BR_PROB_BASE / 2;
2881 uninst_edge->count
2882 = apply_probability (test_bb->count, uninst_edge->probability);
2885 // If we have no previous special cases, and we have PHIs at the beginning
2886 // of the atomic region, this means we have a loop at the beginning of the
2887 // atomic region that shares the first block. This can cause problems with
2888 // the transaction restart abnormal edges to be added in the tm_edges pass.
2889 // Solve this by adding a new empty block to receive the abnormal edges.
2890 if (region->restart_block == region->entry_block
2891 && phi_nodes (region->entry_block))
2893 basic_block empty_bb = create_empty_bb (transaction_bb);
2894 region->restart_block = empty_bb;
2895 add_bb_to_loop (empty_bb, transaction_bb->loop_father);
2897 redirect_edge_pred (fallthru_edge, empty_bb);
2898 make_edge (transaction_bb, empty_bb, EDGE_FALLTHRU);
2901 return NULL;
2904 /* Generate the temporary to be used for the return value of
2905 BUILT_IN_TM_START. */
2907 static void *
2908 generate_tm_state (struct tm_region *region, void *data ATTRIBUTE_UNUSED)
2910 tree tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2911 region->tm_state =
2912 create_tmp_reg (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2914 // Reset the subcode, post optimizations. We'll fill this in
2915 // again as we process blocks.
2916 if (region->exit_blocks)
2918 unsigned int subcode
2919 = gimple_transaction_subcode (region->transaction_stmt);
2921 if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2922 subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2923 | GTMA_MAY_ENTER_IRREVOCABLE
2924 | GTMA_HAS_NO_INSTRUMENTATION);
2925 else
2926 subcode &= GTMA_DECLARATION_MASK;
2927 gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2930 return NULL;
2933 // Propagate flags from inner transactions outwards.
2934 static void
2935 propagate_tm_flags_out (struct tm_region *region)
2937 if (region == NULL)
2938 return;
2939 propagate_tm_flags_out (region->inner);
2941 if (region->outer && region->outer->transaction_stmt)
2943 unsigned s = gimple_transaction_subcode (region->transaction_stmt);
2944 s &= (GTMA_HAVE_ABORT | GTMA_HAVE_LOAD | GTMA_HAVE_STORE
2945 | GTMA_MAY_ENTER_IRREVOCABLE);
2946 s |= gimple_transaction_subcode (region->outer->transaction_stmt);
2947 gimple_transaction_set_subcode (region->outer->transaction_stmt, s);
2950 propagate_tm_flags_out (region->next);
2953 /* Entry point to the MARK phase of TM expansion. Here we replace
2954 transactional memory statements with calls to builtins, and function
2955 calls with their transactional clones (if available). But we don't
2956 yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges. */
2958 static unsigned int
2959 execute_tm_mark (void)
2961 pending_edge_inserts_p = false;
2963 expand_regions (all_tm_regions, generate_tm_state, NULL,
2964 /*traverse_clones=*/true);
2966 tm_log_init ();
2968 vec<tm_region_p> bb_regions
2969 = get_bb_regions_instrumented (/*traverse_clones=*/true,
2970 /*include_uninstrumented_p=*/false);
2971 struct tm_region *r;
2972 unsigned i;
2974 // Expand memory operations into calls into the runtime.
2975 // This collects log entries as well.
2976 FOR_EACH_VEC_ELT (bb_regions, i, r)
2978 if (r != NULL)
2980 if (r->transaction_stmt)
2982 unsigned sub = gimple_transaction_subcode (r->transaction_stmt);
2984 /* If we're sure to go irrevocable, there won't be
2985 anything to expand, since the run-time will go
2986 irrevocable right away. */
2987 if (sub & GTMA_DOES_GO_IRREVOCABLE
2988 && sub & GTMA_MAY_ENTER_IRREVOCABLE)
2989 continue;
2991 expand_block_tm (r, BASIC_BLOCK_FOR_FN (cfun, i));
2995 bb_regions.release ();
2997 // Propagate flags from inner transactions outwards.
2998 propagate_tm_flags_out (all_tm_regions);
3000 // Expand GIMPLE_TRANSACTIONs into calls into the runtime.
3001 expand_regions (all_tm_regions, expand_transaction, NULL,
3002 /*traverse_clones=*/false);
3004 tm_log_emit ();
3005 tm_log_delete ();
3007 if (pending_edge_inserts_p)
3008 gsi_commit_edge_inserts ();
3009 free_dominance_info (CDI_DOMINATORS);
3010 return 0;
3013 namespace {
3015 const pass_data pass_data_tm_mark =
3017 GIMPLE_PASS, /* type */
3018 "tmmark", /* name */
3019 OPTGROUP_NONE, /* optinfo_flags */
3020 TV_TRANS_MEM, /* tv_id */
3021 ( PROP_ssa | PROP_cfg ), /* properties_required */
3022 0, /* properties_provided */
3023 0, /* properties_destroyed */
3024 0, /* todo_flags_start */
3025 TODO_update_ssa, /* todo_flags_finish */
3028 class pass_tm_mark : public gimple_opt_pass
3030 public:
3031 pass_tm_mark (gcc::context *ctxt)
3032 : gimple_opt_pass (pass_data_tm_mark, ctxt)
3035 /* opt_pass methods: */
3036 virtual unsigned int execute (function *) { return execute_tm_mark (); }
3038 }; // class pass_tm_mark
3040 } // anon namespace
3042 gimple_opt_pass *
3043 make_pass_tm_mark (gcc::context *ctxt)
3045 return new pass_tm_mark (ctxt);
3049 /* Create an abnormal edge from STMT at iter, splitting the block
3050 as necessary. Adjust *PNEXT as needed for the split block. */
3052 static inline void
3053 split_bb_make_tm_edge (gimple stmt, basic_block dest_bb,
3054 gimple_stmt_iterator iter, gimple_stmt_iterator *pnext)
3056 basic_block bb = gimple_bb (stmt);
3057 if (!gsi_one_before_end_p (iter))
3059 edge e = split_block (bb, stmt);
3060 *pnext = gsi_start_bb (e->dest);
3062 make_edge (bb, dest_bb, EDGE_ABNORMAL);
3064 // Record the need for the edge for the benefit of the rtl passes.
3065 if (cfun->gimple_df->tm_restart == NULL)
3066 cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
3067 struct_ptr_eq, ggc_free);
3069 struct tm_restart_node dummy;
3070 dummy.stmt = stmt;
3071 dummy.label_or_list = gimple_block_label (dest_bb);
3073 void **slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
3074 struct tm_restart_node *n = (struct tm_restart_node *) *slot;
3075 if (n == NULL)
3077 n = ggc_alloc<tm_restart_node> ();
3078 *n = dummy;
3080 else
3082 tree old = n->label_or_list;
3083 if (TREE_CODE (old) == LABEL_DECL)
3084 old = tree_cons (NULL, old, NULL);
3085 n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
3089 /* Split block BB as necessary for every builtin function we added, and
3090 wire up the abnormal back edges implied by the transaction restart. */
3092 static void
3093 expand_block_edges (struct tm_region *const region, basic_block bb)
3095 gimple_stmt_iterator gsi, next_gsi;
3097 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi = next_gsi)
3099 gimple stmt = gsi_stmt (gsi);
3101 next_gsi = gsi;
3102 gsi_next (&next_gsi);
3104 // ??? Shouldn't we split for any non-pure, non-irrevocable function?
3105 if (gimple_code (stmt) != GIMPLE_CALL
3106 || (gimple_call_flags (stmt) & ECF_TM_BUILTIN) == 0)
3107 continue;
3109 if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_TM_ABORT)
3111 // If we have a ``_transaction_cancel [[outer]]'', there is only
3112 // one abnormal edge: to the transaction marked OUTER.
3113 // All compiler-generated instances of BUILT_IN_TM_ABORT have a
3114 // constant argument, which we can examine here. Users invoking
3115 // TM_ABORT directly get what they deserve.
3116 tree arg = gimple_call_arg (stmt, 0);
3117 if (TREE_CODE (arg) == INTEGER_CST
3118 && (TREE_INT_CST_LOW (arg) & AR_OUTERABORT) != 0
3119 && !decl_is_tm_clone (current_function_decl))
3121 // Find the GTMA_IS_OUTER transaction.
3122 for (struct tm_region *o = region; o; o = o->outer)
3123 if (o->original_transaction_was_outer)
3125 split_bb_make_tm_edge (stmt, o->restart_block,
3126 gsi, &next_gsi);
3127 break;
3130 // Otherwise, the front-end should have semantically checked
3131 // outer aborts, but in either case the target region is not
3132 // within this function.
3133 continue;
3136 // Non-outer, TM aborts have an abnormal edge to the inner-most
3137 // transaction, the one being aborted;
3138 split_bb_make_tm_edge (stmt, region->restart_block, gsi, &next_gsi);
3141 // All TM builtins have an abnormal edge to the outer-most transaction.
3142 // We never restart inner transactions. For tm clones, we know a-priori
3143 // that the outer-most transaction is outside the function.
3144 if (decl_is_tm_clone (current_function_decl))
3145 continue;
3147 if (cfun->gimple_df->tm_restart == NULL)
3148 cfun->gimple_df->tm_restart
3149 = htab_create_ggc (31, struct_ptr_hash, struct_ptr_eq, ggc_free);
3151 // All TM builtins have an abnormal edge to the outer-most transaction.
3152 // We never restart inner transactions.
3153 for (struct tm_region *o = region; o; o = o->outer)
3154 if (!o->outer)
3156 split_bb_make_tm_edge (stmt, o->restart_block, gsi, &next_gsi);
3157 break;
3160 // Delete any tail-call annotation that may have been added.
3161 // The tail-call pass may have mis-identified the commit as being
3162 // a candidate because we had not yet added this restart edge.
3163 gimple_call_set_tail (stmt, false);
3167 /* Entry point to the final expansion of transactional nodes. */
3169 namespace {
3171 const pass_data pass_data_tm_edges =
3173 GIMPLE_PASS, /* type */
3174 "tmedge", /* name */
3175 OPTGROUP_NONE, /* optinfo_flags */
3176 TV_TRANS_MEM, /* tv_id */
3177 ( PROP_ssa | PROP_cfg ), /* properties_required */
3178 0, /* properties_provided */
3179 0, /* properties_destroyed */
3180 0, /* todo_flags_start */
3181 TODO_update_ssa, /* todo_flags_finish */
3184 class pass_tm_edges : public gimple_opt_pass
3186 public:
3187 pass_tm_edges (gcc::context *ctxt)
3188 : gimple_opt_pass (pass_data_tm_edges, ctxt)
3191 /* opt_pass methods: */
3192 virtual unsigned int execute (function *);
3194 }; // class pass_tm_edges
3196 unsigned int
3197 pass_tm_edges::execute (function *fun)
3199 vec<tm_region_p> bb_regions
3200 = get_bb_regions_instrumented (/*traverse_clones=*/false,
3201 /*include_uninstrumented_p=*/true);
3202 struct tm_region *r;
3203 unsigned i;
3205 FOR_EACH_VEC_ELT (bb_regions, i, r)
3206 if (r != NULL)
3207 expand_block_edges (r, BASIC_BLOCK_FOR_FN (fun, i));
3209 bb_regions.release ();
3211 /* We've got to release the dominance info now, to indicate that it
3212 must be rebuilt completely. Otherwise we'll crash trying to update
3213 the SSA web in the TODO section following this pass. */
3214 free_dominance_info (CDI_DOMINATORS);
3215 bitmap_obstack_release (&tm_obstack);
3216 all_tm_regions = NULL;
3218 return 0;
3221 } // anon namespace
3223 gimple_opt_pass *
3224 make_pass_tm_edges (gcc::context *ctxt)
3226 return new pass_tm_edges (ctxt);
3229 /* Helper function for expand_regions. Expand REGION and recurse to
3230 the inner region. Call CALLBACK on each region. CALLBACK returns
3231 NULL to continue the traversal, otherwise a non-null value which
3232 this function will return as well. TRAVERSE_CLONES is true if we
3233 should traverse transactional clones. */
3235 static void *
3236 expand_regions_1 (struct tm_region *region,
3237 void *(*callback)(struct tm_region *, void *),
3238 void *data,
3239 bool traverse_clones)
3241 void *retval = NULL;
3242 if (region->exit_blocks
3243 || (traverse_clones && decl_is_tm_clone (current_function_decl)))
3245 retval = callback (region, data);
3246 if (retval)
3247 return retval;
3249 if (region->inner)
3251 retval = expand_regions (region->inner, callback, data, traverse_clones);
3252 if (retval)
3253 return retval;
3255 return retval;
3258 /* Traverse the regions enclosed and including REGION. Execute
3259 CALLBACK for each region, passing DATA. CALLBACK returns NULL to
3260 continue the traversal, otherwise a non-null value which this
3261 function will return as well. TRAVERSE_CLONES is true if we should
3262 traverse transactional clones. */
3264 static void *
3265 expand_regions (struct tm_region *region,
3266 void *(*callback)(struct tm_region *, void *),
3267 void *data,
3268 bool traverse_clones)
3270 void *retval = NULL;
3271 while (region)
3273 retval = expand_regions_1 (region, callback, data, traverse_clones);
3274 if (retval)
3275 return retval;
3276 region = region->next;
3278 return retval;
3282 /* A unique TM memory operation. */
3283 typedef struct tm_memop
3285 /* Unique ID that all memory operations to the same location have. */
3286 unsigned int value_id;
3287 /* Address of load/store. */
3288 tree addr;
3289 } *tm_memop_t;
3291 /* TM memory operation hashtable helpers. */
3293 struct tm_memop_hasher : typed_free_remove <tm_memop>
3295 typedef tm_memop value_type;
3296 typedef tm_memop compare_type;
3297 static inline hashval_t hash (const value_type *);
3298 static inline bool equal (const value_type *, const compare_type *);
3301 /* Htab support. Return a hash value for a `tm_memop'. */
3302 inline hashval_t
3303 tm_memop_hasher::hash (const value_type *mem)
3305 tree addr = mem->addr;
3306 /* We drill down to the SSA_NAME/DECL for the hash, but equality is
3307 actually done with operand_equal_p (see tm_memop_eq). */
3308 if (TREE_CODE (addr) == ADDR_EXPR)
3309 addr = TREE_OPERAND (addr, 0);
3310 return iterative_hash_expr (addr, 0);
3313 /* Htab support. Return true if two tm_memop's are the same. */
3314 inline bool
3315 tm_memop_hasher::equal (const value_type *mem1, const compare_type *mem2)
3317 return operand_equal_p (mem1->addr, mem2->addr, 0);
3320 /* Sets for solving data flow equations in the memory optimization pass. */
3321 struct tm_memopt_bitmaps
3323 /* Stores available to this BB upon entry. Basically, stores that
3324 dominate this BB. */
3325 bitmap store_avail_in;
3326 /* Stores available at the end of this BB. */
3327 bitmap store_avail_out;
3328 bitmap store_antic_in;
3329 bitmap store_antic_out;
3330 /* Reads available to this BB upon entry. Basically, reads that
3331 dominate this BB. */
3332 bitmap read_avail_in;
3333 /* Reads available at the end of this BB. */
3334 bitmap read_avail_out;
3335 /* Reads performed in this BB. */
3336 bitmap read_local;
3337 /* Writes performed in this BB. */
3338 bitmap store_local;
3340 /* Temporary storage for pass. */
3341 /* Is the current BB in the worklist? */
3342 bool avail_in_worklist_p;
3343 /* Have we visited this BB? */
3344 bool visited_p;
3347 static bitmap_obstack tm_memopt_obstack;
3349 /* Unique counter for TM loads and stores. Loads and stores of the
3350 same address get the same ID. */
3351 static unsigned int tm_memopt_value_id;
3352 static hash_table<tm_memop_hasher> *tm_memopt_value_numbers;
3354 #define STORE_AVAIL_IN(BB) \
3355 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
3356 #define STORE_AVAIL_OUT(BB) \
3357 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
3358 #define STORE_ANTIC_IN(BB) \
3359 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
3360 #define STORE_ANTIC_OUT(BB) \
3361 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
3362 #define READ_AVAIL_IN(BB) \
3363 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
3364 #define READ_AVAIL_OUT(BB) \
3365 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
3366 #define READ_LOCAL(BB) \
3367 ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
3368 #define STORE_LOCAL(BB) \
3369 ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
3370 #define AVAIL_IN_WORKLIST_P(BB) \
3371 ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
3372 #define BB_VISITED_P(BB) \
3373 ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
3375 /* Given a TM load/store in STMT, return the value number for the address
3376 it accesses. */
3378 static unsigned int
3379 tm_memopt_value_number (gimple stmt, enum insert_option op)
3381 struct tm_memop tmpmem, *mem;
3382 tm_memop **slot;
3384 gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
3385 tmpmem.addr = gimple_call_arg (stmt, 0);
3386 slot = tm_memopt_value_numbers->find_slot (&tmpmem, op);
3387 if (*slot)
3388 mem = *slot;
3389 else if (op == INSERT)
3391 mem = XNEW (struct tm_memop);
3392 *slot = mem;
3393 mem->value_id = tm_memopt_value_id++;
3394 mem->addr = tmpmem.addr;
3396 else
3397 gcc_unreachable ();
3398 return mem->value_id;
3401 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL. */
3403 static void
3404 tm_memopt_accumulate_memops (basic_block bb)
3406 gimple_stmt_iterator gsi;
3408 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3410 gimple stmt = gsi_stmt (gsi);
3411 bitmap bits;
3412 unsigned int loc;
3414 if (is_tm_store (stmt))
3415 bits = STORE_LOCAL (bb);
3416 else if (is_tm_load (stmt))
3417 bits = READ_LOCAL (bb);
3418 else
3419 continue;
3421 loc = tm_memopt_value_number (stmt, INSERT);
3422 bitmap_set_bit (bits, loc);
3423 if (dump_file)
3425 fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
3426 is_tm_load (stmt) ? "LOAD" : "STORE", loc,
3427 gimple_bb (stmt)->index);
3428 print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
3429 fprintf (dump_file, "\n");
3434 /* Prettily dump one of the memopt sets. BITS is the bitmap to dump. */
3436 static void
3437 dump_tm_memopt_set (const char *set_name, bitmap bits)
3439 unsigned i;
3440 bitmap_iterator bi;
3441 const char *comma = "";
3443 fprintf (dump_file, "TM memopt: %s: [", set_name);
3444 EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
3446 hash_table<tm_memop_hasher>::iterator hi;
3447 struct tm_memop *mem = NULL;
3449 /* Yeah, yeah, yeah. Whatever. This is just for debugging. */
3450 FOR_EACH_HASH_TABLE_ELEMENT (*tm_memopt_value_numbers, mem, tm_memop_t, hi)
3451 if (mem->value_id == i)
3452 break;
3453 gcc_assert (mem->value_id == i);
3454 fprintf (dump_file, "%s", comma);
3455 comma = ", ";
3456 print_generic_expr (dump_file, mem->addr, 0);
3458 fprintf (dump_file, "]\n");
3461 /* Prettily dump all of the memopt sets in BLOCKS. */
3463 static void
3464 dump_tm_memopt_sets (vec<basic_block> blocks)
3466 size_t i;
3467 basic_block bb;
3469 for (i = 0; blocks.iterate (i, &bb); ++i)
3471 fprintf (dump_file, "------------BB %d---------\n", bb->index);
3472 dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
3473 dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
3474 dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
3475 dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
3476 dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
3477 dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
3481 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB. */
3483 static void
3484 tm_memopt_compute_avin (basic_block bb)
3486 edge e;
3487 unsigned ix;
3489 /* Seed with the AVOUT of any predecessor. */
3490 for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
3492 e = EDGE_PRED (bb, ix);
3493 /* Make sure we have already visited this BB, and is thus
3494 initialized.
3496 If e->src->aux is NULL, this predecessor is actually on an
3497 enclosing transaction. We only care about the current
3498 transaction, so ignore it. */
3499 if (e->src->aux && BB_VISITED_P (e->src))
3501 bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3502 bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3503 break;
3507 for (; ix < EDGE_COUNT (bb->preds); ix++)
3509 e = EDGE_PRED (bb, ix);
3510 if (e->src->aux && BB_VISITED_P (e->src))
3512 bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
3513 bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
3517 BB_VISITED_P (bb) = true;
3520 /* Compute the STORE_ANTIC_IN for the basic block BB. */
3522 static void
3523 tm_memopt_compute_antin (basic_block bb)
3525 edge e;
3526 unsigned ix;
3528 /* Seed with the ANTIC_OUT of any successor. */
3529 for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
3531 e = EDGE_SUCC (bb, ix);
3532 /* Make sure we have already visited this BB, and is thus
3533 initialized. */
3534 if (BB_VISITED_P (e->dest))
3536 bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3537 break;
3541 for (; ix < EDGE_COUNT (bb->succs); ix++)
3543 e = EDGE_SUCC (bb, ix);
3544 if (BB_VISITED_P (e->dest))
3545 bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3548 BB_VISITED_P (bb) = true;
3551 /* Compute the AVAIL sets for every basic block in BLOCKS.
3553 We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3555 AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3556 AVAIL_IN[bb] = intersect (AVAIL_OUT[predecessors])
3558 This is basically what we do in lcm's compute_available(), but here
3559 we calculate two sets of sets (one for STOREs and one for READs),
3560 and we work on a region instead of the entire CFG.
3562 REGION is the TM region.
3563 BLOCKS are the basic blocks in the region. */
3565 static void
3566 tm_memopt_compute_available (struct tm_region *region,
3567 vec<basic_block> blocks)
3569 edge e;
3570 basic_block *worklist, *qin, *qout, *qend, bb;
3571 unsigned int qlen, i;
3572 edge_iterator ei;
3573 bool changed;
3575 /* Allocate a worklist array/queue. Entries are only added to the
3576 list if they were not already on the list. So the size is
3577 bounded by the number of basic blocks in the region. */
3578 qlen = blocks.length () - 1;
3579 qin = qout = worklist =
3580 XNEWVEC (basic_block, qlen);
3582 /* Put every block in the region on the worklist. */
3583 for (i = 0; blocks.iterate (i, &bb); ++i)
3585 /* Seed AVAIL_OUT with the LOCAL set. */
3586 bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3587 bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3589 AVAIL_IN_WORKLIST_P (bb) = true;
3590 /* No need to insert the entry block, since it has an AVIN of
3591 null, and an AVOUT that has already been seeded in. */
3592 if (bb != region->entry_block)
3593 *qin++ = bb;
3596 /* The entry block has been initialized with the local sets. */
3597 BB_VISITED_P (region->entry_block) = true;
3599 qin = worklist;
3600 qend = &worklist[qlen];
3602 /* Iterate until the worklist is empty. */
3603 while (qlen)
3605 /* Take the first entry off the worklist. */
3606 bb = *qout++;
3607 qlen--;
3609 if (qout >= qend)
3610 qout = worklist;
3612 /* This block can be added to the worklist again if necessary. */
3613 AVAIL_IN_WORKLIST_P (bb) = false;
3614 tm_memopt_compute_avin (bb);
3616 /* Note: We do not add the LOCAL sets here because we already
3617 seeded the AVAIL_OUT sets with them. */
3618 changed = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3619 changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3620 if (changed
3621 && (region->exit_blocks == NULL
3622 || !bitmap_bit_p (region->exit_blocks, bb->index)))
3623 /* If the out state of this block changed, then we need to add
3624 its successors to the worklist if they are not already in. */
3625 FOR_EACH_EDGE (e, ei, bb->succs)
3626 if (!AVAIL_IN_WORKLIST_P (e->dest)
3627 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
3629 *qin++ = e->dest;
3630 AVAIL_IN_WORKLIST_P (e->dest) = true;
3631 qlen++;
3633 if (qin >= qend)
3634 qin = worklist;
3638 free (worklist);
3640 if (dump_file)
3641 dump_tm_memopt_sets (blocks);
3644 /* Compute ANTIC sets for every basic block in BLOCKS.
3646 We compute STORE_ANTIC_OUT as follows:
3648 STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3649 STORE_ANTIC_IN[bb] = intersect(STORE_ANTIC_OUT[successors])
3651 REGION is the TM region.
3652 BLOCKS are the basic blocks in the region. */
3654 static void
3655 tm_memopt_compute_antic (struct tm_region *region,
3656 vec<basic_block> blocks)
3658 edge e;
3659 basic_block *worklist, *qin, *qout, *qend, bb;
3660 unsigned int qlen;
3661 int i;
3662 edge_iterator ei;
3664 /* Allocate a worklist array/queue. Entries are only added to the
3665 list if they were not already on the list. So the size is
3666 bounded by the number of basic blocks in the region. */
3667 qin = qout = worklist = XNEWVEC (basic_block, blocks.length ());
3669 for (qlen = 0, i = blocks.length () - 1; i >= 0; --i)
3671 bb = blocks[i];
3673 /* Seed ANTIC_OUT with the LOCAL set. */
3674 bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3676 /* Put every block in the region on the worklist. */
3677 AVAIL_IN_WORKLIST_P (bb) = true;
3678 /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3679 and their ANTIC_OUT has already been seeded in. */
3680 if (region->exit_blocks
3681 && !bitmap_bit_p (region->exit_blocks, bb->index))
3683 qlen++;
3684 *qin++ = bb;
3688 /* The exit blocks have been initialized with the local sets. */
3689 if (region->exit_blocks)
3691 unsigned int i;
3692 bitmap_iterator bi;
3693 EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3694 BB_VISITED_P (BASIC_BLOCK_FOR_FN (cfun, i)) = true;
3697 qin = worklist;
3698 qend = &worklist[qlen];
3700 /* Iterate until the worklist is empty. */
3701 while (qlen)
3703 /* Take the first entry off the worklist. */
3704 bb = *qout++;
3705 qlen--;
3707 if (qout >= qend)
3708 qout = worklist;
3710 /* This block can be added to the worklist again if necessary. */
3711 AVAIL_IN_WORKLIST_P (bb) = false;
3712 tm_memopt_compute_antin (bb);
3714 /* Note: We do not add the LOCAL sets here because we already
3715 seeded the ANTIC_OUT sets with them. */
3716 if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3717 && bb != region->entry_block)
3718 /* If the out state of this block changed, then we need to add
3719 its predecessors to the worklist if they are not already in. */
3720 FOR_EACH_EDGE (e, ei, bb->preds)
3721 if (!AVAIL_IN_WORKLIST_P (e->src))
3723 *qin++ = e->src;
3724 AVAIL_IN_WORKLIST_P (e->src) = true;
3725 qlen++;
3727 if (qin >= qend)
3728 qin = worklist;
3732 free (worklist);
3734 if (dump_file)
3735 dump_tm_memopt_sets (blocks);
3738 /* Offsets of load variants from TM_LOAD. For example,
3739 BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3740 See gtm-builtins.def. */
3741 #define TRANSFORM_RAR 1
3742 #define TRANSFORM_RAW 2
3743 #define TRANSFORM_RFW 3
3744 /* Offsets of store variants from TM_STORE. */
3745 #define TRANSFORM_WAR 1
3746 #define TRANSFORM_WAW 2
3748 /* Inform about a load/store optimization. */
3750 static void
3751 dump_tm_memopt_transform (gimple stmt)
3753 if (dump_file)
3755 fprintf (dump_file, "TM memopt: transforming: ");
3756 print_gimple_stmt (dump_file, stmt, 0, 0);
3757 fprintf (dump_file, "\n");
3761 /* Perform a read/write optimization. Replaces the TM builtin in STMT
3762 by a builtin that is OFFSET entries down in the builtins table in
3763 gtm-builtins.def. */
3765 static void
3766 tm_memopt_transform_stmt (unsigned int offset,
3767 gimple stmt,
3768 gimple_stmt_iterator *gsi)
3770 tree fn = gimple_call_fn (stmt);
3771 gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3772 TREE_OPERAND (fn, 0)
3773 = builtin_decl_explicit ((enum built_in_function)
3774 (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3775 + offset));
3776 gimple_call_set_fn (stmt, fn);
3777 gsi_replace (gsi, stmt, true);
3778 dump_tm_memopt_transform (stmt);
3781 /* Perform the actual TM memory optimization transformations in the
3782 basic blocks in BLOCKS. */
3784 static void
3785 tm_memopt_transform_blocks (vec<basic_block> blocks)
3787 size_t i;
3788 basic_block bb;
3789 gimple_stmt_iterator gsi;
3791 for (i = 0; blocks.iterate (i, &bb); ++i)
3793 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3795 gimple stmt = gsi_stmt (gsi);
3796 bitmap read_avail = READ_AVAIL_IN (bb);
3797 bitmap store_avail = STORE_AVAIL_IN (bb);
3798 bitmap store_antic = STORE_ANTIC_OUT (bb);
3799 unsigned int loc;
3801 if (is_tm_simple_load (stmt))
3803 loc = tm_memopt_value_number (stmt, NO_INSERT);
3804 if (store_avail && bitmap_bit_p (store_avail, loc))
3805 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3806 else if (store_antic && bitmap_bit_p (store_antic, loc))
3808 tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3809 bitmap_set_bit (store_avail, loc);
3811 else if (read_avail && bitmap_bit_p (read_avail, loc))
3812 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3813 else
3814 bitmap_set_bit (read_avail, loc);
3816 else if (is_tm_simple_store (stmt))
3818 loc = tm_memopt_value_number (stmt, NO_INSERT);
3819 if (store_avail && bitmap_bit_p (store_avail, loc))
3820 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3821 else
3823 if (read_avail && bitmap_bit_p (read_avail, loc))
3824 tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3825 bitmap_set_bit (store_avail, loc);
3832 /* Return a new set of bitmaps for a BB. */
3834 static struct tm_memopt_bitmaps *
3835 tm_memopt_init_sets (void)
3837 struct tm_memopt_bitmaps *b
3838 = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3839 b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3840 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3841 b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3842 b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3843 b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3844 b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3845 b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3846 b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3847 b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3848 return b;
3851 /* Free sets computed for each BB. */
3853 static void
3854 tm_memopt_free_sets (vec<basic_block> blocks)
3856 size_t i;
3857 basic_block bb;
3859 for (i = 0; blocks.iterate (i, &bb); ++i)
3860 bb->aux = NULL;
3863 /* Clear the visited bit for every basic block in BLOCKS. */
3865 static void
3866 tm_memopt_clear_visited (vec<basic_block> blocks)
3868 size_t i;
3869 basic_block bb;
3871 for (i = 0; blocks.iterate (i, &bb); ++i)
3872 BB_VISITED_P (bb) = false;
3875 /* Replace TM load/stores with hints for the runtime. We handle
3876 things like read-after-write, write-after-read, read-after-read,
3877 read-for-write, etc. */
3879 static unsigned int
3880 execute_tm_memopt (void)
3882 struct tm_region *region;
3883 vec<basic_block> bbs;
3885 tm_memopt_value_id = 0;
3886 tm_memopt_value_numbers = new hash_table<tm_memop_hasher> (10);
3888 for (region = all_tm_regions; region; region = region->next)
3890 /* All the TM stores/loads in the current region. */
3891 size_t i;
3892 basic_block bb;
3894 bitmap_obstack_initialize (&tm_memopt_obstack);
3896 /* Save all BBs for the current region. */
3897 bbs = get_tm_region_blocks (region->entry_block,
3898 region->exit_blocks,
3899 region->irr_blocks,
3900 NULL,
3901 false);
3903 /* Collect all the memory operations. */
3904 for (i = 0; bbs.iterate (i, &bb); ++i)
3906 bb->aux = tm_memopt_init_sets ();
3907 tm_memopt_accumulate_memops (bb);
3910 /* Solve data flow equations and transform each block accordingly. */
3911 tm_memopt_clear_visited (bbs);
3912 tm_memopt_compute_available (region, bbs);
3913 tm_memopt_clear_visited (bbs);
3914 tm_memopt_compute_antic (region, bbs);
3915 tm_memopt_transform_blocks (bbs);
3917 tm_memopt_free_sets (bbs);
3918 bbs.release ();
3919 bitmap_obstack_release (&tm_memopt_obstack);
3920 tm_memopt_value_numbers->empty ();
3923 delete tm_memopt_value_numbers;
3924 tm_memopt_value_numbers = NULL;
3925 return 0;
3928 namespace {
3930 const pass_data pass_data_tm_memopt =
3932 GIMPLE_PASS, /* type */
3933 "tmmemopt", /* name */
3934 OPTGROUP_NONE, /* optinfo_flags */
3935 TV_TRANS_MEM, /* tv_id */
3936 ( PROP_ssa | PROP_cfg ), /* properties_required */
3937 0, /* properties_provided */
3938 0, /* properties_destroyed */
3939 0, /* todo_flags_start */
3940 0, /* todo_flags_finish */
3943 class pass_tm_memopt : public gimple_opt_pass
3945 public:
3946 pass_tm_memopt (gcc::context *ctxt)
3947 : gimple_opt_pass (pass_data_tm_memopt, ctxt)
3950 /* opt_pass methods: */
3951 virtual bool gate (function *) { return flag_tm && optimize > 0; }
3952 virtual unsigned int execute (function *) { return execute_tm_memopt (); }
3954 }; // class pass_tm_memopt
3956 } // anon namespace
3958 gimple_opt_pass *
3959 make_pass_tm_memopt (gcc::context *ctxt)
3961 return new pass_tm_memopt (ctxt);
3965 /* Interprocedual analysis for the creation of transactional clones.
3966 The aim of this pass is to find which functions are referenced in
3967 a non-irrevocable transaction context, and for those over which
3968 we have control (or user directive), create a version of the
3969 function which uses only the transactional interface to reference
3970 protected memories. This analysis proceeds in several steps:
3972 (1) Collect the set of all possible transactional clones:
3974 (a) For all local public functions marked tm_callable, push
3975 it onto the tm_callee queue.
3977 (b) For all local functions, scan for calls in transaction blocks.
3978 Push the caller and callee onto the tm_caller and tm_callee
3979 queues. Count the number of callers for each callee.
3981 (c) For each local function on the callee list, assume we will
3982 create a transactional clone. Push *all* calls onto the
3983 callee queues; count the number of clone callers separately
3984 to the number of original callers.
3986 (2) Propagate irrevocable status up the dominator tree:
3988 (a) Any external function on the callee list that is not marked
3989 tm_callable is irrevocable. Push all callers of such onto
3990 a worklist.
3992 (b) For each function on the worklist, mark each block that
3993 contains an irrevocable call. Use the AND operator to
3994 propagate that mark up the dominator tree.
3996 (c) If we reach the entry block for a possible transactional
3997 clone, then the transactional clone is irrevocable, and
3998 we should not create the clone after all. Push all
3999 callers onto the worklist.
4001 (d) Place tm_irrevocable calls at the beginning of the relevant
4002 blocks. Special case here is the entry block for the entire
4003 transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
4004 the library to begin the region in serial mode. Decrement
4005 the call count for all callees in the irrevocable region.
4007 (3) Create the transactional clones:
4009 Any tm_callee that still has a non-zero call count is cloned.
4012 /* This structure is stored in the AUX field of each cgraph_node. */
4013 struct tm_ipa_cg_data
4015 /* The clone of the function that got created. */
4016 struct cgraph_node *clone;
4018 /* The tm regions in the normal function. */
4019 struct tm_region *all_tm_regions;
4021 /* The blocks of the normal/clone functions that contain irrevocable
4022 calls, or blocks that are post-dominated by irrevocable calls. */
4023 bitmap irrevocable_blocks_normal;
4024 bitmap irrevocable_blocks_clone;
4026 /* The blocks of the normal function that are involved in transactions. */
4027 bitmap transaction_blocks_normal;
4029 /* The number of callers to the transactional clone of this function
4030 from normal and transactional clones respectively. */
4031 unsigned tm_callers_normal;
4032 unsigned tm_callers_clone;
4034 /* True if all calls to this function's transactional clone
4035 are irrevocable. Also automatically true if the function
4036 has no transactional clone. */
4037 bool is_irrevocable;
4039 /* Flags indicating the presence of this function in various queues. */
4040 bool in_callee_queue;
4041 bool in_worklist;
4043 /* Flags indicating the kind of scan desired while in the worklist. */
4044 bool want_irr_scan_normal;
4047 typedef vec<cgraph_node *> cgraph_node_queue;
4049 /* Return the ipa data associated with NODE, allocating zeroed memory
4050 if necessary. TRAVERSE_ALIASES is true if we must traverse aliases
4051 and set *NODE accordingly. */
4053 static struct tm_ipa_cg_data *
4054 get_cg_data (struct cgraph_node **node, bool traverse_aliases)
4056 struct tm_ipa_cg_data *d;
4058 if (traverse_aliases && (*node)->alias)
4059 *node = (*node)->get_alias_target ();
4061 d = (struct tm_ipa_cg_data *) (*node)->aux;
4063 if (d == NULL)
4065 d = (struct tm_ipa_cg_data *)
4066 obstack_alloc (&tm_obstack.obstack, sizeof (*d));
4067 (*node)->aux = (void *) d;
4068 memset (d, 0, sizeof (*d));
4071 return d;
4074 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
4075 it is already present. */
4077 static void
4078 maybe_push_queue (struct cgraph_node *node,
4079 cgraph_node_queue *queue_p, bool *in_queue_p)
4081 if (!*in_queue_p)
4083 *in_queue_p = true;
4084 queue_p->safe_push (node);
4088 /* Duplicate the basic blocks in QUEUE for use in the uninstrumented
4089 code path. QUEUE are the basic blocks inside the transaction
4090 represented in REGION.
4092 Later in split_code_paths() we will add the conditional to choose
4093 between the two alternatives. */
4095 static void
4096 ipa_uninstrument_transaction (struct tm_region *region,
4097 vec<basic_block> queue)
4099 gimple transaction = region->transaction_stmt;
4100 basic_block transaction_bb = gimple_bb (transaction);
4101 int n = queue.length ();
4102 basic_block *new_bbs = XNEWVEC (basic_block, n);
4104 copy_bbs (queue.address (), n, new_bbs, NULL, 0, NULL, NULL, transaction_bb,
4105 true);
4106 edge e = make_edge (transaction_bb, new_bbs[0], EDGE_TM_UNINSTRUMENTED);
4107 add_phi_args_after_copy (new_bbs, n, e);
4109 // Now we will have a GIMPLE_ATOMIC with 3 possible edges out of it.
4110 // a) EDGE_FALLTHRU into the transaction
4111 // b) EDGE_TM_ABORT out of the transaction
4112 // c) EDGE_TM_UNINSTRUMENTED into the uninstrumented blocks.
4114 free (new_bbs);
4117 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
4118 Queue all callees within block BB. */
4120 static void
4121 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
4122 basic_block bb, bool for_clone)
4124 gimple_stmt_iterator gsi;
4126 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4128 gimple stmt = gsi_stmt (gsi);
4129 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4131 tree fndecl = gimple_call_fndecl (stmt);
4132 if (fndecl)
4134 struct tm_ipa_cg_data *d;
4135 unsigned *pcallers;
4136 struct cgraph_node *node;
4138 if (is_tm_ending_fndecl (fndecl))
4139 continue;
4140 if (find_tm_replacement_function (fndecl))
4141 continue;
4143 node = cgraph_node::get (fndecl);
4144 gcc_assert (node != NULL);
4145 d = get_cg_data (&node, true);
4147 pcallers = (for_clone ? &d->tm_callers_clone
4148 : &d->tm_callers_normal);
4149 *pcallers += 1;
4151 maybe_push_queue (node, callees_p, &d->in_callee_queue);
4157 /* Scan all calls in NODE that are within a transaction region,
4158 and push the resulting nodes into the callee queue. */
4160 static void
4161 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
4162 cgraph_node_queue *callees_p)
4164 struct tm_region *r;
4166 d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
4167 d->all_tm_regions = all_tm_regions;
4169 for (r = all_tm_regions; r; r = r->next)
4171 vec<basic_block> bbs;
4172 basic_block bb;
4173 unsigned i;
4175 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
4176 d->transaction_blocks_normal, false);
4178 // Generate the uninstrumented code path for this transaction.
4179 ipa_uninstrument_transaction (r, bbs);
4181 FOR_EACH_VEC_ELT (bbs, i, bb)
4182 ipa_tm_scan_calls_block (callees_p, bb, false);
4184 bbs.release ();
4187 // ??? copy_bbs should maintain cgraph edges for the blocks as it is
4188 // copying them, rather than forcing us to do this externally.
4189 cgraph_edge::rebuild_edges ();
4191 // ??? In ipa_uninstrument_transaction we don't try to update dominators
4192 // because copy_bbs doesn't return a VEC like iterate_fix_dominators expects.
4193 // Instead, just release dominators here so update_ssa recomputes them.
4194 free_dominance_info (CDI_DOMINATORS);
4196 // When building the uninstrumented code path, copy_bbs will have invoked
4197 // create_new_def_for starting an "ssa update context". There is only one
4198 // instance of this context, so resolve ssa updates before moving on to
4199 // the next function.
4200 update_ssa (TODO_update_ssa);
4203 /* Scan all calls in NODE as if this is the transactional clone,
4204 and push the destinations into the callee queue. */
4206 static void
4207 ipa_tm_scan_calls_clone (struct cgraph_node *node,
4208 cgraph_node_queue *callees_p)
4210 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
4211 basic_block bb;
4213 FOR_EACH_BB_FN (bb, fn)
4214 ipa_tm_scan_calls_block (callees_p, bb, true);
4217 /* The function NODE has been detected to be irrevocable. Push all
4218 of its callers onto WORKLIST for the purpose of re-scanning them. */
4220 static void
4221 ipa_tm_note_irrevocable (struct cgraph_node *node,
4222 cgraph_node_queue *worklist_p)
4224 struct tm_ipa_cg_data *d = get_cg_data (&node, true);
4225 struct cgraph_edge *e;
4227 d->is_irrevocable = true;
4229 for (e = node->callers; e ; e = e->next_caller)
4231 basic_block bb;
4232 struct cgraph_node *caller;
4234 /* Don't examine recursive calls. */
4235 if (e->caller == node)
4236 continue;
4237 /* Even if we think we can go irrevocable, believe the user
4238 above all. */
4239 if (is_tm_safe_or_pure (e->caller->decl))
4240 continue;
4242 caller = e->caller;
4243 d = get_cg_data (&caller, true);
4245 /* Check if the callee is in a transactional region. If so,
4246 schedule the function for normal re-scan as well. */
4247 bb = gimple_bb (e->call_stmt);
4248 gcc_assert (bb != NULL);
4249 if (d->transaction_blocks_normal
4250 && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
4251 d->want_irr_scan_normal = true;
4253 maybe_push_queue (caller, worklist_p, &d->in_worklist);
4257 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
4258 within the block is irrevocable. */
4260 static bool
4261 ipa_tm_scan_irr_block (basic_block bb)
4263 gimple_stmt_iterator gsi;
4264 tree fn;
4266 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4268 gimple stmt = gsi_stmt (gsi);
4269 switch (gimple_code (stmt))
4271 case GIMPLE_ASSIGN:
4272 if (gimple_assign_single_p (stmt))
4274 tree lhs = gimple_assign_lhs (stmt);
4275 tree rhs = gimple_assign_rhs1 (stmt);
4276 if (volatile_var_p (lhs) || volatile_var_p (rhs))
4277 return true;
4279 break;
4281 case GIMPLE_CALL:
4283 tree lhs = gimple_call_lhs (stmt);
4284 if (lhs && volatile_var_p (lhs))
4285 return true;
4287 if (is_tm_pure_call (stmt))
4288 break;
4290 fn = gimple_call_fn (stmt);
4292 /* Functions with the attribute are by definition irrevocable. */
4293 if (is_tm_irrevocable (fn))
4294 return true;
4296 /* For direct function calls, go ahead and check for replacement
4297 functions, or transitive irrevocable functions. For indirect
4298 functions, we'll ask the runtime. */
4299 if (TREE_CODE (fn) == ADDR_EXPR)
4301 struct tm_ipa_cg_data *d;
4302 struct cgraph_node *node;
4304 fn = TREE_OPERAND (fn, 0);
4305 if (is_tm_ending_fndecl (fn))
4306 break;
4307 if (find_tm_replacement_function (fn))
4308 break;
4310 node = cgraph_node::get (fn);
4311 d = get_cg_data (&node, true);
4313 /* Return true if irrevocable, but above all, believe
4314 the user. */
4315 if (d->is_irrevocable
4316 && !is_tm_safe_or_pure (fn))
4317 return true;
4319 break;
4322 case GIMPLE_ASM:
4323 /* ??? The Approved Method of indicating that an inline
4324 assembly statement is not relevant to the transaction
4325 is to wrap it in a __tm_waiver block. This is not
4326 yet implemented, so we can't check for it. */
4327 if (is_tm_safe (current_function_decl))
4329 tree t = build1 (NOP_EXPR, void_type_node, size_zero_node);
4330 SET_EXPR_LOCATION (t, gimple_location (stmt));
4331 error ("%Kasm not allowed in %<transaction_safe%> function", t);
4333 return true;
4335 default:
4336 break;
4340 return false;
4343 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
4344 for new irrevocable blocks, marking them in NEW_IRR. Don't bother
4345 scanning past OLD_IRR or EXIT_BLOCKS. */
4347 static bool
4348 ipa_tm_scan_irr_blocks (vec<basic_block> *pqueue, bitmap new_irr,
4349 bitmap old_irr, bitmap exit_blocks)
4351 bool any_new_irr = false;
4352 edge e;
4353 edge_iterator ei;
4354 bitmap visited_blocks = BITMAP_ALLOC (NULL);
4358 basic_block bb = pqueue->pop ();
4360 /* Don't re-scan blocks we know already are irrevocable. */
4361 if (old_irr && bitmap_bit_p (old_irr, bb->index))
4362 continue;
4364 if (ipa_tm_scan_irr_block (bb))
4366 bitmap_set_bit (new_irr, bb->index);
4367 any_new_irr = true;
4369 else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
4371 FOR_EACH_EDGE (e, ei, bb->succs)
4372 if (!bitmap_bit_p (visited_blocks, e->dest->index))
4374 bitmap_set_bit (visited_blocks, e->dest->index);
4375 pqueue->safe_push (e->dest);
4379 while (!pqueue->is_empty ());
4381 BITMAP_FREE (visited_blocks);
4383 return any_new_irr;
4386 /* Propagate the irrevocable property both up and down the dominator tree.
4387 BB is the current block being scanned; EXIT_BLOCKS are the edges of the
4388 TM regions; OLD_IRR are the results of a previous scan of the dominator
4389 tree which has been fully propagated; NEW_IRR is the set of new blocks
4390 which are gaining the irrevocable property during the current scan. */
4392 static void
4393 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
4394 bitmap old_irr, bitmap exit_blocks)
4396 vec<basic_block> bbs;
4397 bitmap all_region_blocks;
4399 /* If this block is in the old set, no need to rescan. */
4400 if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
4401 return;
4403 all_region_blocks = BITMAP_ALLOC (&tm_obstack);
4404 bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
4405 all_region_blocks, false);
4408 basic_block bb = bbs.pop ();
4409 bool this_irr = bitmap_bit_p (new_irr, bb->index);
4410 bool all_son_irr = false;
4411 edge_iterator ei;
4412 edge e;
4414 /* Propagate up. If my children are, I am too, but we must have
4415 at least one child that is. */
4416 if (!this_irr)
4418 FOR_EACH_EDGE (e, ei, bb->succs)
4420 if (!bitmap_bit_p (new_irr, e->dest->index))
4422 all_son_irr = false;
4423 break;
4425 else
4426 all_son_irr = true;
4428 if (all_son_irr)
4430 /* Add block to new_irr if it hasn't already been processed. */
4431 if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
4433 bitmap_set_bit (new_irr, bb->index);
4434 this_irr = true;
4439 /* Propagate down to everyone we immediately dominate. */
4440 if (this_irr)
4442 basic_block son;
4443 for (son = first_dom_son (CDI_DOMINATORS, bb);
4444 son;
4445 son = next_dom_son (CDI_DOMINATORS, son))
4447 /* Make sure block is actually in a TM region, and it
4448 isn't already in old_irr. */
4449 if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
4450 && bitmap_bit_p (all_region_blocks, son->index))
4451 bitmap_set_bit (new_irr, son->index);
4455 while (!bbs.is_empty ());
4457 BITMAP_FREE (all_region_blocks);
4458 bbs.release ();
4461 static void
4462 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
4464 gimple_stmt_iterator gsi;
4466 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4468 gimple stmt = gsi_stmt (gsi);
4469 if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
4471 tree fndecl = gimple_call_fndecl (stmt);
4472 if (fndecl)
4474 struct tm_ipa_cg_data *d;
4475 unsigned *pcallers;
4476 struct cgraph_node *tnode;
4478 if (is_tm_ending_fndecl (fndecl))
4479 continue;
4480 if (find_tm_replacement_function (fndecl))
4481 continue;
4483 tnode = cgraph_node::get (fndecl);
4484 d = get_cg_data (&tnode, true);
4486 pcallers = (for_clone ? &d->tm_callers_clone
4487 : &d->tm_callers_normal);
4489 gcc_assert (*pcallers > 0);
4490 *pcallers -= 1;
4496 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
4497 as well as other irrevocable actions such as inline assembly. Mark all
4498 such blocks as irrevocable and decrement the number of calls to
4499 transactional clones. Return true if, for the transactional clone, the
4500 entire function is irrevocable. */
4502 static bool
4503 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
4505 struct tm_ipa_cg_data *d;
4506 bitmap new_irr, old_irr;
4507 bool ret = false;
4509 /* Builtin operators (operator new, and such). */
4510 if (DECL_STRUCT_FUNCTION (node->decl) == NULL
4511 || DECL_STRUCT_FUNCTION (node->decl)->cfg == NULL)
4512 return false;
4514 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4515 calculate_dominance_info (CDI_DOMINATORS);
4517 d = get_cg_data (&node, true);
4518 auto_vec<basic_block, 10> queue;
4519 new_irr = BITMAP_ALLOC (&tm_obstack);
4521 /* Scan each tm region, propagating irrevocable status through the tree. */
4522 if (for_clone)
4524 old_irr = d->irrevocable_blocks_clone;
4525 queue.quick_push (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
4526 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
4528 ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
4529 new_irr,
4530 old_irr, NULL);
4531 ret = bitmap_bit_p (new_irr,
4532 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun))->index);
4535 else
4537 struct tm_region *region;
4539 old_irr = d->irrevocable_blocks_normal;
4540 for (region = d->all_tm_regions; region; region = region->next)
4542 queue.quick_push (region->entry_block);
4543 if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
4544 region->exit_blocks))
4545 ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
4546 region->exit_blocks);
4550 /* If we found any new irrevocable blocks, reduce the call count for
4551 transactional clones within the irrevocable blocks. Save the new
4552 set of irrevocable blocks for next time. */
4553 if (!bitmap_empty_p (new_irr))
4555 bitmap_iterator bmi;
4556 unsigned i;
4558 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4559 ipa_tm_decrement_clone_counts (BASIC_BLOCK_FOR_FN (cfun, i),
4560 for_clone);
4562 if (old_irr)
4564 bitmap_ior_into (old_irr, new_irr);
4565 BITMAP_FREE (new_irr);
4567 else if (for_clone)
4568 d->irrevocable_blocks_clone = new_irr;
4569 else
4570 d->irrevocable_blocks_normal = new_irr;
4572 if (dump_file && new_irr)
4574 const char *dname;
4575 bitmap_iterator bmi;
4576 unsigned i;
4578 dname = lang_hooks.decl_printable_name (current_function_decl, 2);
4579 EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
4580 fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
4583 else
4584 BITMAP_FREE (new_irr);
4586 pop_cfun ();
4588 return ret;
4591 /* Return true if, for the transactional clone of NODE, any call
4592 may enter irrevocable mode. */
4594 static bool
4595 ipa_tm_mayenterirr_function (struct cgraph_node *node)
4597 struct tm_ipa_cg_data *d;
4598 tree decl;
4599 unsigned flags;
4601 d = get_cg_data (&node, true);
4602 decl = node->decl;
4603 flags = flags_from_decl_or_type (decl);
4605 /* Handle some TM builtins. Ordinarily these aren't actually generated
4606 at this point, but handling these functions when written in by the
4607 user makes it easier to build unit tests. */
4608 if (flags & ECF_TM_BUILTIN)
4609 return false;
4611 /* Filter out all functions that are marked. */
4612 if (flags & ECF_TM_PURE)
4613 return false;
4614 if (is_tm_safe (decl))
4615 return false;
4616 if (is_tm_irrevocable (decl))
4617 return true;
4618 if (is_tm_callable (decl))
4619 return true;
4620 if (find_tm_replacement_function (decl))
4621 return true;
4623 /* If we aren't seeing the final version of the function we don't
4624 know what it will contain at runtime. */
4625 if (node->get_availability () < AVAIL_AVAILABLE)
4626 return true;
4628 /* If the function must go irrevocable, then of course true. */
4629 if (d->is_irrevocable)
4630 return true;
4632 /* If there are any blocks marked irrevocable, then the function
4633 as a whole may enter irrevocable. */
4634 if (d->irrevocable_blocks_clone)
4635 return true;
4637 /* We may have previously marked this function as tm_may_enter_irr;
4638 see pass_diagnose_tm_blocks. */
4639 if (node->local.tm_may_enter_irr)
4640 return true;
4642 /* Recurse on the main body for aliases. In general, this will
4643 result in one of the bits above being set so that we will not
4644 have to recurse next time. */
4645 if (node->alias)
4646 return ipa_tm_mayenterirr_function (cgraph_node::get (node->thunk.alias));
4648 /* What remains is unmarked local functions without items that force
4649 the function to go irrevocable. */
4650 return false;
4653 /* Diagnose calls from transaction_safe functions to unmarked
4654 functions that are determined to not be safe. */
4656 static void
4657 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4659 struct cgraph_edge *e;
4661 for (e = node->callees; e ; e = e->next_callee)
4662 if (!is_tm_callable (e->callee->decl)
4663 && e->callee->local.tm_may_enter_irr)
4664 error_at (gimple_location (e->call_stmt),
4665 "unsafe function call %qD within "
4666 "%<transaction_safe%> function", e->callee->decl);
4669 /* Diagnose call from atomic transactions to unmarked functions
4670 that are determined to not be safe. */
4672 static void
4673 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4674 struct tm_region *all_tm_regions)
4676 struct tm_region *r;
4678 for (r = all_tm_regions; r ; r = r->next)
4679 if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4681 /* Atomic transactions can be nested inside relaxed. */
4682 if (r->inner)
4683 ipa_tm_diagnose_transaction (node, r->inner);
4685 else
4687 vec<basic_block> bbs;
4688 gimple_stmt_iterator gsi;
4689 basic_block bb;
4690 size_t i;
4692 bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4693 r->irr_blocks, NULL, false);
4695 for (i = 0; bbs.iterate (i, &bb); ++i)
4696 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4698 gimple stmt = gsi_stmt (gsi);
4699 tree fndecl;
4701 if (gimple_code (stmt) == GIMPLE_ASM)
4703 error_at (gimple_location (stmt),
4704 "asm not allowed in atomic transaction");
4705 continue;
4708 if (!is_gimple_call (stmt))
4709 continue;
4710 fndecl = gimple_call_fndecl (stmt);
4712 /* Indirect function calls have been diagnosed already. */
4713 if (!fndecl)
4714 continue;
4716 /* Stop at the end of the transaction. */
4717 if (is_tm_ending_fndecl (fndecl))
4719 if (bitmap_bit_p (r->exit_blocks, bb->index))
4720 break;
4721 continue;
4724 /* Marked functions have been diagnosed already. */
4725 if (is_tm_pure_call (stmt))
4726 continue;
4727 if (is_tm_callable (fndecl))
4728 continue;
4730 if (cgraph_node::local_info (fndecl)->tm_may_enter_irr)
4731 error_at (gimple_location (stmt),
4732 "unsafe function call %qD within "
4733 "atomic transaction", fndecl);
4736 bbs.release ();
4740 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4741 OLD_DECL. The returned value is a freshly malloced pointer that
4742 should be freed by the caller. */
4744 static tree
4745 tm_mangle (tree old_asm_id)
4747 const char *old_asm_name;
4748 char *tm_name;
4749 void *alloc = NULL;
4750 struct demangle_component *dc;
4751 tree new_asm_id;
4753 /* Determine if the symbol is already a valid C++ mangled name. Do this
4754 even for C, which might be interfacing with C++ code via appropriately
4755 ugly identifiers. */
4756 /* ??? We could probably do just as well checking for "_Z" and be done. */
4757 old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4758 dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4760 if (dc == NULL)
4762 char length[8];
4764 do_unencoded:
4765 sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4766 tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4768 else
4770 old_asm_name += 2; /* Skip _Z */
4772 switch (dc->type)
4774 case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4775 case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4776 /* Don't play silly games, you! */
4777 goto do_unencoded;
4779 case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4780 /* I'd really like to know if we can ever be passed one of
4781 these from the C++ front end. The Logical Thing would
4782 seem that hidden-alias should be outer-most, so that we
4783 get hidden-alias of a transaction-clone and not vice-versa. */
4784 old_asm_name += 2;
4785 break;
4787 default:
4788 break;
4791 tm_name = concat ("_ZGTt", old_asm_name, NULL);
4793 free (alloc);
4795 new_asm_id = get_identifier (tm_name);
4796 free (tm_name);
4798 return new_asm_id;
4801 static inline void
4802 ipa_tm_mark_force_output_node (struct cgraph_node *node)
4804 node->mark_force_output ();
4805 node->analyzed = true;
4808 static inline void
4809 ipa_tm_mark_forced_by_abi_node (struct cgraph_node *node)
4811 node->forced_by_abi = true;
4812 node->analyzed = true;
4815 /* Callback data for ipa_tm_create_version_alias. */
4816 struct create_version_alias_info
4818 struct cgraph_node *old_node;
4819 tree new_decl;
4822 /* A subroutine of ipa_tm_create_version, called via
4823 cgraph_for_node_and_aliases. Create new tm clones for each of
4824 the existing aliases. */
4825 static bool
4826 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4828 struct create_version_alias_info *info
4829 = (struct create_version_alias_info *)data;
4830 tree old_decl, new_decl, tm_name;
4831 struct cgraph_node *new_node;
4833 if (!node->cpp_implicit_alias)
4834 return false;
4836 old_decl = node->decl;
4837 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4838 new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4839 TREE_CODE (old_decl), tm_name,
4840 TREE_TYPE (old_decl));
4842 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4843 SET_DECL_RTL (new_decl, NULL);
4845 /* Based loosely on C++'s make_alias_for(). */
4846 TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4847 DECL_CONTEXT (new_decl) = DECL_CONTEXT (old_decl);
4848 DECL_LANG_SPECIFIC (new_decl) = DECL_LANG_SPECIFIC (old_decl);
4849 TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4850 DECL_EXTERNAL (new_decl) = 0;
4851 DECL_ARTIFICIAL (new_decl) = 1;
4852 TREE_ADDRESSABLE (new_decl) = 1;
4853 TREE_USED (new_decl) = 1;
4854 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4856 /* Perform the same remapping to the comdat group. */
4857 if (DECL_ONE_ONLY (new_decl))
4858 varpool_node::get (new_decl)->set_comdat_group
4859 (tm_mangle (decl_comdat_group_id (old_decl)));
4861 new_node = cgraph_node::create_same_body_alias (new_decl, info->new_decl);
4862 new_node->tm_clone = true;
4863 new_node->externally_visible = info->old_node->externally_visible;
4864 new_node->no_reorder = info->old_node->no_reorder;
4865 /* ?? Do not traverse aliases here. */
4866 get_cg_data (&node, false)->clone = new_node;
4868 record_tm_clone_pair (old_decl, new_decl);
4870 if (info->old_node->force_output
4871 || info->old_node->ref_list.first_referring ())
4872 ipa_tm_mark_force_output_node (new_node);
4873 if (info->old_node->forced_by_abi)
4874 ipa_tm_mark_forced_by_abi_node (new_node);
4875 return false;
4878 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4879 appropriate for the transactional clone. */
4881 static void
4882 ipa_tm_create_version (struct cgraph_node *old_node)
4884 tree new_decl, old_decl, tm_name;
4885 struct cgraph_node *new_node;
4887 old_decl = old_node->decl;
4888 new_decl = copy_node (old_decl);
4890 /* DECL_ASSEMBLER_NAME needs to be set before we call
4891 cgraph_copy_node_for_versioning below, because cgraph_node will
4892 fill the assembler_name_hash. */
4893 tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4894 SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4895 SET_DECL_RTL (new_decl, NULL);
4896 TREE_SYMBOL_REFERENCED (tm_name) = 1;
4898 /* Perform the same remapping to the comdat group. */
4899 if (DECL_ONE_ONLY (new_decl))
4900 varpool_node::get (new_decl)->set_comdat_group
4901 (tm_mangle (DECL_COMDAT_GROUP (old_decl)));
4903 gcc_assert (!old_node->ipa_transforms_to_apply.exists ());
4904 new_node = old_node->create_version_clone (new_decl, vNULL, NULL);
4905 new_node->local.local = false;
4906 new_node->externally_visible = old_node->externally_visible;
4907 new_node->lowered = true;
4908 new_node->tm_clone = 1;
4909 get_cg_data (&old_node, true)->clone = new_node;
4911 if (old_node->get_availability () >= AVAIL_INTERPOSABLE)
4913 /* Remap extern inline to static inline. */
4914 /* ??? Is it worth trying to use make_decl_one_only? */
4915 if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4917 DECL_EXTERNAL (new_decl) = 0;
4918 TREE_PUBLIC (new_decl) = 0;
4919 DECL_WEAK (new_decl) = 0;
4922 tree_function_versioning (old_decl, new_decl,
4923 NULL, false, NULL,
4924 false, NULL, NULL);
4927 record_tm_clone_pair (old_decl, new_decl);
4929 symtab->call_cgraph_insertion_hooks (new_node);
4930 if (old_node->force_output
4931 || old_node->ref_list.first_referring ())
4932 ipa_tm_mark_force_output_node (new_node);
4933 if (old_node->forced_by_abi)
4934 ipa_tm_mark_forced_by_abi_node (new_node);
4936 /* Do the same thing, but for any aliases of the original node. */
4938 struct create_version_alias_info data;
4939 data.old_node = old_node;
4940 data.new_decl = new_decl;
4941 old_node->call_for_symbol_thunks_and_aliases (ipa_tm_create_version_alias,
4942 &data, true);
4946 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB. */
4948 static void
4949 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4950 basic_block bb)
4952 gimple_stmt_iterator gsi;
4953 gimple g;
4955 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4957 g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4958 1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4960 split_block_after_labels (bb);
4961 gsi = gsi_after_labels (bb);
4962 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4964 node->create_edge (cgraph_node::get_create
4965 (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4966 g, 0,
4967 compute_call_stmt_bb_frequency (node->decl,
4968 gimple_bb (g)));
4971 /* Construct a call to TM_GETTMCLONE and insert it before GSI. */
4973 static bool
4974 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4975 struct tm_region *region,
4976 gimple_stmt_iterator *gsi, gimple stmt)
4978 tree gettm_fn, ret, old_fn, callfn;
4979 gimple g, g2;
4980 bool safe;
4982 old_fn = gimple_call_fn (stmt);
4984 if (TREE_CODE (old_fn) == ADDR_EXPR)
4986 tree fndecl = TREE_OPERAND (old_fn, 0);
4987 tree clone = get_tm_clone_pair (fndecl);
4989 /* By transforming the call into a TM_GETTMCLONE, we are
4990 technically taking the address of the original function and
4991 its clone. Explain this so inlining will know this function
4992 is needed. */
4993 cgraph_node::get (fndecl)->mark_address_taken () ;
4994 if (clone)
4995 cgraph_node::get (clone)->mark_address_taken ();
4998 safe = is_tm_safe (TREE_TYPE (old_fn));
4999 gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
5000 : BUILT_IN_TM_GETTMCLONE_IRR);
5001 ret = create_tmp_var (ptr_type_node, NULL);
5003 if (!safe)
5004 transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
5006 /* Discard OBJ_TYPE_REF, since we weren't able to fold it. */
5007 if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
5008 old_fn = OBJ_TYPE_REF_EXPR (old_fn);
5010 g = gimple_build_call (gettm_fn, 1, old_fn);
5011 ret = make_ssa_name (ret, g);
5012 gimple_call_set_lhs (g, ret);
5014 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5016 node->create_edge (cgraph_node::get_create (gettm_fn), g, 0,
5017 compute_call_stmt_bb_frequency (node->decl,
5018 gimple_bb (g)));
5020 /* Cast return value from tm_gettmclone* into appropriate function
5021 pointer. */
5022 callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
5023 g2 = gimple_build_assign (callfn,
5024 fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
5025 callfn = make_ssa_name (callfn, g2);
5026 gimple_assign_set_lhs (g2, callfn);
5027 gsi_insert_before (gsi, g2, GSI_SAME_STMT);
5029 /* ??? This is a hack to preserve the NOTHROW bit on the call,
5030 which we would have derived from the decl. Failure to save
5031 this bit means we might have to split the basic block. */
5032 if (gimple_call_nothrow_p (stmt))
5033 gimple_call_set_nothrow (stmt, true);
5035 gimple_call_set_fn (stmt, callfn);
5037 /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
5038 for a call statement. Fix it. */
5040 tree lhs = gimple_call_lhs (stmt);
5041 tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
5042 if (lhs
5043 && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
5045 tree temp;
5047 temp = create_tmp_reg (rettype, 0);
5048 gimple_call_set_lhs (stmt, temp);
5050 g2 = gimple_build_assign (lhs,
5051 fold_build1 (VIEW_CONVERT_EXPR,
5052 TREE_TYPE (lhs), temp));
5053 gsi_insert_after (gsi, g2, GSI_SAME_STMT);
5057 update_stmt (stmt);
5058 cgraph_edge *e = cgraph_node::get (current_function_decl)->get_edge (stmt);
5059 if (e && e->indirect_info)
5060 e->indirect_info->polymorphic = false;
5062 return true;
5065 /* Helper function for ipa_tm_transform_calls*. Given a call
5066 statement in GSI which resides inside transaction REGION, redirect
5067 the call to either its wrapper function, or its clone. */
5069 static void
5070 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
5071 struct tm_region *region,
5072 gimple_stmt_iterator *gsi,
5073 bool *need_ssa_rename_p)
5075 gimple stmt = gsi_stmt (*gsi);
5076 struct cgraph_node *new_node;
5077 struct cgraph_edge *e = node->get_edge (stmt);
5078 tree fndecl = gimple_call_fndecl (stmt);
5080 /* For indirect calls, pass the address through the runtime. */
5081 if (fndecl == NULL)
5083 *need_ssa_rename_p |=
5084 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5085 return;
5088 /* Handle some TM builtins. Ordinarily these aren't actually generated
5089 at this point, but handling these functions when written in by the
5090 user makes it easier to build unit tests. */
5091 if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
5092 return;
5094 /* Fixup recursive calls inside clones. */
5095 /* ??? Why did cgraph_copy_node_for_versioning update the call edges
5096 for recursion but not update the call statements themselves? */
5097 if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
5099 gimple_call_set_fndecl (stmt, current_function_decl);
5100 return;
5103 /* If there is a replacement, use it. */
5104 fndecl = find_tm_replacement_function (fndecl);
5105 if (fndecl)
5107 new_node = cgraph_node::get_create (fndecl);
5109 /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
5111 We can't do this earlier in record_tm_replacement because
5112 cgraph_remove_unreachable_nodes is called before we inject
5113 references to the node. Further, we can't do this in some
5114 nice central place in ipa_tm_execute because we don't have
5115 the exact list of wrapper functions that would be used.
5116 Marking more wrappers than necessary results in the creation
5117 of unnecessary cgraph_nodes, which can cause some of the
5118 other IPA passes to crash.
5120 We do need to mark these nodes so that we get the proper
5121 result in expand_call_tm. */
5122 /* ??? This seems broken. How is it that we're marking the
5123 CALLEE as may_enter_irr? Surely we should be marking the
5124 CALLER. Also note that find_tm_replacement_function also
5125 contains mappings into the TM runtime, e.g. memcpy. These
5126 we know won't go irrevocable. */
5127 new_node->local.tm_may_enter_irr = 1;
5129 else
5131 struct tm_ipa_cg_data *d;
5132 struct cgraph_node *tnode = e->callee;
5134 d = get_cg_data (&tnode, true);
5135 new_node = d->clone;
5137 /* As we've already skipped pure calls and appropriate builtins,
5138 and we've already marked irrevocable blocks, if we can't come
5139 up with a static replacement, then ask the runtime. */
5140 if (new_node == NULL)
5142 *need_ssa_rename_p |=
5143 ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
5144 return;
5147 fndecl = new_node->decl;
5150 e->redirect_callee (new_node);
5151 gimple_call_set_fndecl (stmt, fndecl);
5154 /* Helper function for ipa_tm_transform_calls. For a given BB,
5155 install calls to tm_irrevocable when IRR_BLOCKS are reached,
5156 redirect other calls to the generated transactional clone. */
5158 static bool
5159 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
5160 basic_block bb, bitmap irr_blocks)
5162 gimple_stmt_iterator gsi;
5163 bool need_ssa_rename = false;
5165 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5167 ipa_tm_insert_irr_call (node, region, bb);
5168 return true;
5171 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5173 gimple stmt = gsi_stmt (gsi);
5175 if (!is_gimple_call (stmt))
5176 continue;
5177 if (is_tm_pure_call (stmt))
5178 continue;
5180 /* Redirect edges to the appropriate replacement or clone. */
5181 ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
5184 return need_ssa_rename;
5187 /* Walk the CFG for REGION, beginning at BB. Install calls to
5188 tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
5189 the generated transactional clone. */
5191 static bool
5192 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
5193 basic_block bb, bitmap irr_blocks)
5195 bool need_ssa_rename = false;
5196 edge e;
5197 edge_iterator ei;
5198 auto_vec<basic_block> queue;
5199 bitmap visited_blocks = BITMAP_ALLOC (NULL);
5201 queue.safe_push (bb);
5204 bb = queue.pop ();
5206 need_ssa_rename |=
5207 ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
5209 if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
5210 continue;
5212 if (region && bitmap_bit_p (region->exit_blocks, bb->index))
5213 continue;
5215 FOR_EACH_EDGE (e, ei, bb->succs)
5216 if (!bitmap_bit_p (visited_blocks, e->dest->index))
5218 bitmap_set_bit (visited_blocks, e->dest->index);
5219 queue.safe_push (e->dest);
5222 while (!queue.is_empty ());
5224 BITMAP_FREE (visited_blocks);
5226 return need_ssa_rename;
5229 /* Transform the calls within the TM regions within NODE. */
5231 static void
5232 ipa_tm_transform_transaction (struct cgraph_node *node)
5234 struct tm_ipa_cg_data *d;
5235 struct tm_region *region;
5236 bool need_ssa_rename = false;
5238 d = get_cg_data (&node, true);
5240 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5241 calculate_dominance_info (CDI_DOMINATORS);
5243 for (region = d->all_tm_regions; region; region = region->next)
5245 /* If we're sure to go irrevocable, don't transform anything. */
5246 if (d->irrevocable_blocks_normal
5247 && bitmap_bit_p (d->irrevocable_blocks_normal,
5248 region->entry_block->index))
5250 transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE
5251 | GTMA_MAY_ENTER_IRREVOCABLE
5252 | GTMA_HAS_NO_INSTRUMENTATION);
5253 continue;
5256 need_ssa_rename |=
5257 ipa_tm_transform_calls (node, region, region->entry_block,
5258 d->irrevocable_blocks_normal);
5261 if (need_ssa_rename)
5262 update_ssa (TODO_update_ssa_only_virtuals);
5264 pop_cfun ();
5267 /* Transform the calls within the transactional clone of NODE. */
5269 static void
5270 ipa_tm_transform_clone (struct cgraph_node *node)
5272 struct tm_ipa_cg_data *d;
5273 bool need_ssa_rename;
5275 d = get_cg_data (&node, true);
5277 /* If this function makes no calls and has no irrevocable blocks,
5278 then there's nothing to do. */
5279 /* ??? Remove non-aborting top-level transactions. */
5280 if (!node->callees && !node->indirect_calls && !d->irrevocable_blocks_clone)
5281 return;
5283 push_cfun (DECL_STRUCT_FUNCTION (d->clone->decl));
5284 calculate_dominance_info (CDI_DOMINATORS);
5286 need_ssa_rename =
5287 ipa_tm_transform_calls (d->clone, NULL,
5288 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
5289 d->irrevocable_blocks_clone);
5291 if (need_ssa_rename)
5292 update_ssa (TODO_update_ssa_only_virtuals);
5294 pop_cfun ();
5297 /* Main entry point for the transactional memory IPA pass. */
5299 static unsigned int
5300 ipa_tm_execute (void)
5302 cgraph_node_queue tm_callees = cgraph_node_queue ();
5303 /* List of functions that will go irrevocable. */
5304 cgraph_node_queue irr_worklist = cgraph_node_queue ();
5306 struct cgraph_node *node;
5307 struct tm_ipa_cg_data *d;
5308 enum availability a;
5309 unsigned int i;
5311 #ifdef ENABLE_CHECKING
5312 cgraph_node::verify_cgraph_nodes ();
5313 #endif
5315 bitmap_obstack_initialize (&tm_obstack);
5316 initialize_original_copy_tables ();
5318 /* For all local functions marked tm_callable, queue them. */
5319 FOR_EACH_DEFINED_FUNCTION (node)
5320 if (is_tm_callable (node->decl)
5321 && node->get_availability () >= AVAIL_INTERPOSABLE)
5323 d = get_cg_data (&node, true);
5324 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5327 /* For all local reachable functions... */
5328 FOR_EACH_DEFINED_FUNCTION (node)
5329 if (node->lowered
5330 && node->get_availability () >= AVAIL_INTERPOSABLE)
5332 /* ... marked tm_pure, record that fact for the runtime by
5333 indicating that the pure function is its own tm_callable.
5334 No need to do this if the function's address can't be taken. */
5335 if (is_tm_pure (node->decl))
5337 if (!node->local.local)
5338 record_tm_clone_pair (node->decl, node->decl);
5339 continue;
5342 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
5343 calculate_dominance_info (CDI_DOMINATORS);
5345 tm_region_init (NULL);
5346 if (all_tm_regions)
5348 d = get_cg_data (&node, true);
5350 /* Scan for calls that are in each transaction, and
5351 generate the uninstrumented code path. */
5352 ipa_tm_scan_calls_transaction (d, &tm_callees);
5354 /* Put it in the worklist so we can scan the function
5355 later (ipa_tm_scan_irr_function) and mark the
5356 irrevocable blocks. */
5357 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5358 d->want_irr_scan_normal = true;
5361 pop_cfun ();
5364 /* For every local function on the callee list, scan as if we will be
5365 creating a transactional clone, queueing all new functions we find
5366 along the way. */
5367 for (i = 0; i < tm_callees.length (); ++i)
5369 node = tm_callees[i];
5370 a = node->get_availability ();
5371 d = get_cg_data (&node, true);
5373 /* Put it in the worklist so we can scan the function later
5374 (ipa_tm_scan_irr_function) and mark the irrevocable
5375 blocks. */
5376 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5378 /* Some callees cannot be arbitrarily cloned. These will always be
5379 irrevocable. Mark these now, so that we need not scan them. */
5380 if (is_tm_irrevocable (node->decl))
5381 ipa_tm_note_irrevocable (node, &irr_worklist);
5382 else if (a <= AVAIL_NOT_AVAILABLE
5383 && !is_tm_safe_or_pure (node->decl))
5384 ipa_tm_note_irrevocable (node, &irr_worklist);
5385 else if (a >= AVAIL_INTERPOSABLE)
5387 if (!tree_versionable_function_p (node->decl))
5388 ipa_tm_note_irrevocable (node, &irr_worklist);
5389 else if (!d->is_irrevocable)
5391 /* If this is an alias, make sure its base is queued as well.
5392 we need not scan the callees now, as the base will do. */
5393 if (node->alias)
5395 node = cgraph_node::get (node->thunk.alias);
5396 d = get_cg_data (&node, true);
5397 maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
5398 continue;
5401 /* Add all nodes called by this function into
5402 tm_callees as well. */
5403 ipa_tm_scan_calls_clone (node, &tm_callees);
5408 /* Iterate scans until no more work to be done. Prefer not to use
5409 vec::pop because the worklist tends to follow a breadth-first
5410 search of the callgraph, which should allow convergance with a
5411 minimum number of scans. But we also don't want the worklist
5412 array to grow without bound, so we shift the array up periodically. */
5413 for (i = 0; i < irr_worklist.length (); ++i)
5415 if (i > 256 && i == irr_worklist.length () / 8)
5417 irr_worklist.block_remove (0, i);
5418 i = 0;
5421 node = irr_worklist[i];
5422 d = get_cg_data (&node, true);
5423 d->in_worklist = false;
5425 if (d->want_irr_scan_normal)
5427 d->want_irr_scan_normal = false;
5428 ipa_tm_scan_irr_function (node, false);
5430 if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
5431 ipa_tm_note_irrevocable (node, &irr_worklist);
5434 /* For every function on the callee list, collect the tm_may_enter_irr
5435 bit on the node. */
5436 irr_worklist.truncate (0);
5437 for (i = 0; i < tm_callees.length (); ++i)
5439 node = tm_callees[i];
5440 if (ipa_tm_mayenterirr_function (node))
5442 d = get_cg_data (&node, true);
5443 gcc_assert (d->in_worklist == false);
5444 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
5448 /* Propagate the tm_may_enter_irr bit to callers until stable. */
5449 for (i = 0; i < irr_worklist.length (); ++i)
5451 struct cgraph_node *caller;
5452 struct cgraph_edge *e;
5453 struct ipa_ref *ref;
5455 if (i > 256 && i == irr_worklist.length () / 8)
5457 irr_worklist.block_remove (0, i);
5458 i = 0;
5461 node = irr_worklist[i];
5462 d = get_cg_data (&node, true);
5463 d->in_worklist = false;
5464 node->local.tm_may_enter_irr = true;
5466 /* Propagate back to normal callers. */
5467 for (e = node->callers; e ; e = e->next_caller)
5469 caller = e->caller;
5470 if (!is_tm_safe_or_pure (caller->decl)
5471 && !caller->local.tm_may_enter_irr)
5473 d = get_cg_data (&caller, true);
5474 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5478 /* Propagate back to referring aliases as well. */
5479 FOR_EACH_ALIAS (node, ref)
5481 caller = dyn_cast<cgraph_node *> (ref->referring);
5482 if (!caller->local.tm_may_enter_irr)
5484 /* ?? Do not traverse aliases here. */
5485 d = get_cg_data (&caller, false);
5486 maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
5491 /* Now validate all tm_safe functions, and all atomic regions in
5492 other functions. */
5493 FOR_EACH_DEFINED_FUNCTION (node)
5494 if (node->lowered
5495 && node->get_availability () >= AVAIL_INTERPOSABLE)
5497 d = get_cg_data (&node, true);
5498 if (is_tm_safe (node->decl))
5499 ipa_tm_diagnose_tm_safe (node);
5500 else if (d->all_tm_regions)
5501 ipa_tm_diagnose_transaction (node, d->all_tm_regions);
5504 /* Create clones. Do those that are not irrevocable and have a
5505 positive call count. Do those publicly visible functions that
5506 the user directed us to clone. */
5507 for (i = 0; i < tm_callees.length (); ++i)
5509 bool doit = false;
5511 node = tm_callees[i];
5512 if (node->cpp_implicit_alias)
5513 continue;
5515 a = node->get_availability ();
5516 d = get_cg_data (&node, true);
5518 if (a <= AVAIL_NOT_AVAILABLE)
5519 doit = is_tm_callable (node->decl);
5520 else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
5521 doit = true;
5522 else if (!d->is_irrevocable
5523 && d->tm_callers_normal + d->tm_callers_clone > 0)
5524 doit = true;
5526 if (doit)
5527 ipa_tm_create_version (node);
5530 /* Redirect calls to the new clones, and insert irrevocable marks. */
5531 for (i = 0; i < tm_callees.length (); ++i)
5533 node = tm_callees[i];
5534 if (node->analyzed)
5536 d = get_cg_data (&node, true);
5537 if (d->clone)
5538 ipa_tm_transform_clone (node);
5541 FOR_EACH_DEFINED_FUNCTION (node)
5542 if (node->lowered
5543 && node->get_availability () >= AVAIL_INTERPOSABLE)
5545 d = get_cg_data (&node, true);
5546 if (d->all_tm_regions)
5547 ipa_tm_transform_transaction (node);
5550 /* Free and clear all data structures. */
5551 tm_callees.release ();
5552 irr_worklist.release ();
5553 bitmap_obstack_release (&tm_obstack);
5554 free_original_copy_tables ();
5556 FOR_EACH_FUNCTION (node)
5557 node->aux = NULL;
5559 #ifdef ENABLE_CHECKING
5560 cgraph_node::verify_cgraph_nodes ();
5561 #endif
5563 return 0;
5566 namespace {
5568 const pass_data pass_data_ipa_tm =
5570 SIMPLE_IPA_PASS, /* type */
5571 "tmipa", /* name */
5572 OPTGROUP_NONE, /* optinfo_flags */
5573 TV_TRANS_MEM, /* tv_id */
5574 ( PROP_ssa | PROP_cfg ), /* properties_required */
5575 0, /* properties_provided */
5576 0, /* properties_destroyed */
5577 0, /* todo_flags_start */
5578 0, /* todo_flags_finish */
5581 class pass_ipa_tm : public simple_ipa_opt_pass
5583 public:
5584 pass_ipa_tm (gcc::context *ctxt)
5585 : simple_ipa_opt_pass (pass_data_ipa_tm, ctxt)
5588 /* opt_pass methods: */
5589 virtual bool gate (function *) { return flag_tm; }
5590 virtual unsigned int execute (function *) { return ipa_tm_execute (); }
5592 }; // class pass_ipa_tm
5594 } // anon namespace
5596 simple_ipa_opt_pass *
5597 make_pass_ipa_tm (gcc::context *ctxt)
5599 return new pass_ipa_tm (ctxt);
5602 #include "gt-trans-mem.h"