OSDN Git Service

347183b15689b8e3b49e7cb4224cd320dff91639
[pf3gnuchains/gcc-fork.git] / gcc / trans-mem.c
1 /* Passes for transactional memory support.
2    Copyright (C) 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
3
4    This file is part of GCC.
5
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.
10
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.
15
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/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tree.h"
24 #include "gimple.h"
25 #include "tree-flow.h"
26 #include "tree-pass.h"
27 #include "tree-inline.h"
28 #include "diagnostic-core.h"
29 #include "demangle.h"
30 #include "output.h"
31 #include "trans-mem.h"
32 #include "params.h"
33 #include "target.h"
34 #include "langhooks.h"
35 #include "tree-pretty-print.h"
36 #include "gimple-pretty-print.h"
37
38
39 #define PROB_VERY_UNLIKELY      (REG_BR_PROB_BASE / 2000 - 1)
40 #define PROB_ALWAYS             (REG_BR_PROB_BASE)
41
42 #define A_RUNINSTRUMENTEDCODE   0x0001
43 #define A_RUNUNINSTRUMENTEDCODE 0x0002
44 #define A_SAVELIVEVARIABLES     0x0004
45 #define A_RESTORELIVEVARIABLES  0x0008
46 #define A_ABORTTRANSACTION      0x0010
47
48 #define AR_USERABORT            0x0001
49 #define AR_USERRETRY            0x0002
50 #define AR_TMCONFLICT           0x0004
51 #define AR_EXCEPTIONBLOCKABORT  0x0008
52 #define AR_OUTERABORT           0x0010
53
54 #define MODE_SERIALIRREVOCABLE  0x0000
55
56
57 /* The representation of a transaction changes several times during the
58    lowering process.  In the beginning, in the front-end we have the
59    GENERIC tree TRANSACTION_EXPR.  For example,
60
61         __transaction {
62           local++;
63           if (++global == 10)
64             __tm_abort;
65         }
66
67   During initial gimplification (gimplify.c) the TRANSACTION_EXPR node is
68   trivially replaced with a GIMPLE_TRANSACTION node.
69
70   During pass_lower_tm, we examine the body of transactions looking
71   for aborts.  Transactions that do not contain an abort may be
72   merged into an outer transaction.  We also add a TRY-FINALLY node
73   to arrange for the transaction to be committed on any exit.
74
75   [??? Think about how this arrangement affects throw-with-commit
76   and throw-with-abort operations.  In this case we want the TRY to
77   handle gotos, but not to catch any exceptions because the transaction
78   will already be closed.]
79
80         GIMPLE_TRANSACTION [label=NULL] {
81           try {
82             local = local + 1;
83             t0 = global;
84             t1 = t0 + 1;
85             global = t1;
86             if (t1 == 10)
87               __builtin___tm_abort ();
88           } finally {
89             __builtin___tm_commit ();
90           }
91         }
92
93   During pass_lower_eh, we create EH regions for the transactions,
94   intermixed with the regular EH stuff.  This gives us a nice persistent
95   mapping (all the way through rtl) from transactional memory operation
96   back to the transaction, which allows us to get the abnormal edges
97   correct to model transaction aborts and restarts:
98
99         GIMPLE_TRANSACTION [label=over]
100         local = local + 1;
101         t0 = global;
102         t1 = t0 + 1;
103         global = t1;
104         if (t1 == 10)
105           __builtin___tm_abort ();
106         __builtin___tm_commit ();
107         over:
108
109   This is the end of all_lowering_passes, and so is what is present
110   during the IPA passes, and through all of the optimization passes.
111
112   During pass_ipa_tm, we examine all GIMPLE_TRANSACTION blocks in all
113   functions and mark functions for cloning.
114
115   At the end of gimple optimization, before exiting SSA form,
116   pass_tm_edges replaces statements that perform transactional
117   memory operations with the appropriate TM builtins, and swap
118   out function calls with their transactional clones.  At this
119   point we introduce the abnormal transaction restart edges and
120   complete lowering of the GIMPLE_TRANSACTION node.
121
122         x = __builtin___tm_start (MAY_ABORT);
123         eh_label:
124         if (x & abort_transaction)
125           goto over;
126         local = local + 1;
127         t0 = __builtin___tm_load (global);
128         t1 = t0 + 1;
129         __builtin___tm_store (&global, t1);
130         if (t1 == 10)
131           __builtin___tm_abort ();
132         __builtin___tm_commit ();
133         over:
134 */
135
136 \f
137 /* Return the attributes we want to examine for X, or NULL if it's not
138    something we examine.  We look at function types, but allow pointers
139    to function types and function decls and peek through.  */
140
141 static tree
142 get_attrs_for (const_tree x)
143 {
144   switch (TREE_CODE (x))
145     {
146     case FUNCTION_DECL:
147       return TYPE_ATTRIBUTES (TREE_TYPE (x));
148       break;
149
150     default:
151       if (TYPE_P (x))
152         return NULL;
153       x = TREE_TYPE (x);
154       if (TREE_CODE (x) != POINTER_TYPE)
155         return NULL;
156       /* FALLTHRU */
157
158     case POINTER_TYPE:
159       x = TREE_TYPE (x);
160       if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
161         return NULL;
162       /* FALLTHRU */
163
164     case FUNCTION_TYPE:
165     case METHOD_TYPE:
166       return TYPE_ATTRIBUTES (x);
167     }
168 }
169
170 /* Return true if X has been marked TM_PURE.  */
171
172 bool
173 is_tm_pure (const_tree x)
174 {
175   unsigned flags;
176
177   switch (TREE_CODE (x))
178     {
179     case FUNCTION_DECL:
180     case FUNCTION_TYPE:
181     case METHOD_TYPE:
182       break;
183
184     default:
185       if (TYPE_P (x))
186         return false;
187       x = TREE_TYPE (x);
188       if (TREE_CODE (x) != POINTER_TYPE)
189         return false;
190       /* FALLTHRU */
191
192     case POINTER_TYPE:
193       x = TREE_TYPE (x);
194       if (TREE_CODE (x) != FUNCTION_TYPE && TREE_CODE (x) != METHOD_TYPE)
195         return false;
196       break;
197     }
198
199   flags = flags_from_decl_or_type (x);
200   return (flags & ECF_TM_PURE) != 0;
201 }
202
203 /* Return true if X has been marked TM_IRREVOCABLE.  */
204
205 static bool
206 is_tm_irrevocable (tree x)
207 {
208   tree attrs = get_attrs_for (x);
209
210   if (attrs && lookup_attribute ("transaction_unsafe", attrs))
211     return true;
212
213   /* A call to the irrevocable builtin is by definition,
214      irrevocable.  */
215   if (TREE_CODE (x) == ADDR_EXPR)
216     x = TREE_OPERAND (x, 0);
217   if (TREE_CODE (x) == FUNCTION_DECL
218       && DECL_BUILT_IN_CLASS (x) == BUILT_IN_NORMAL
219       && DECL_FUNCTION_CODE (x) == BUILT_IN_TM_IRREVOCABLE)
220     return true;
221
222   return false;
223 }
224
225 /* Return true if X has been marked TM_SAFE.  */
226
227 bool
228 is_tm_safe (const_tree x)
229 {
230   if (flag_tm)
231     {
232       tree attrs = get_attrs_for (x);
233       if (attrs)
234         {
235           if (lookup_attribute ("transaction_safe", attrs))
236             return true;
237           if (lookup_attribute ("transaction_may_cancel_outer", attrs))
238             return true;
239         }
240     }
241   return false;
242 }
243
244 /* Return true if CALL is const, or tm_pure.  */
245
246 static bool
247 is_tm_pure_call (gimple call)
248 {
249   tree fn = gimple_call_fn (call);
250
251   if (TREE_CODE (fn) == ADDR_EXPR)
252     {
253       fn = TREE_OPERAND (fn, 0);
254       gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
255     }
256   else
257     fn = TREE_TYPE (fn);
258
259   return is_tm_pure (fn);
260 }
261
262 /* Return true if X has been marked TM_CALLABLE.  */
263
264 static bool
265 is_tm_callable (tree x)
266 {
267   tree attrs = get_attrs_for (x);
268   if (attrs)
269     {
270       if (lookup_attribute ("transaction_callable", attrs))
271         return true;
272       if (lookup_attribute ("transaction_safe", attrs))
273         return true;
274       if (lookup_attribute ("transaction_may_cancel_outer", attrs))
275         return true;
276     }
277   return false;
278 }
279
280 /* Return true if X has been marked TRANSACTION_MAY_CANCEL_OUTER.  */
281
282 bool
283 is_tm_may_cancel_outer (tree x)
284 {
285   tree attrs = get_attrs_for (x);
286   if (attrs)
287     return lookup_attribute ("transaction_may_cancel_outer", attrs) != NULL;
288   return false;
289 }
290
291 /* Return true for built in functions that "end" a transaction.   */
292
293 bool
294 is_tm_ending_fndecl (tree fndecl)
295 {
296   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
297     switch (DECL_FUNCTION_CODE (fndecl))
298       {
299       case BUILT_IN_TM_COMMIT:
300       case BUILT_IN_TM_COMMIT_EH:
301       case BUILT_IN_TM_ABORT:
302       case BUILT_IN_TM_IRREVOCABLE:
303         return true;
304       default:
305         break;
306       }
307
308   return false;
309 }
310
311 /* Return true if STMT is a TM load.  */
312
313 static bool
314 is_tm_load (gimple stmt)
315 {
316   tree fndecl;
317
318   if (gimple_code (stmt) != GIMPLE_CALL)
319     return false;
320
321   fndecl = gimple_call_fndecl (stmt);
322   return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
323           && BUILTIN_TM_LOAD_P (DECL_FUNCTION_CODE (fndecl)));
324 }
325
326 /* Same as above, but for simple TM loads, that is, not the
327    after-write, after-read, etc optimized variants.  */
328
329 static bool
330 is_tm_simple_load (gimple stmt)
331 {
332   tree fndecl;
333
334   if (gimple_code (stmt) != GIMPLE_CALL)
335     return false;
336
337   fndecl = gimple_call_fndecl (stmt);
338   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
339     {
340       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
341       return (fcode == BUILT_IN_TM_LOAD_1
342               || fcode == BUILT_IN_TM_LOAD_2
343               || fcode == BUILT_IN_TM_LOAD_4
344               || fcode == BUILT_IN_TM_LOAD_8
345               || fcode == BUILT_IN_TM_LOAD_FLOAT
346               || fcode == BUILT_IN_TM_LOAD_DOUBLE
347               || fcode == BUILT_IN_TM_LOAD_LDOUBLE
348               || fcode == BUILT_IN_TM_LOAD_M64
349               || fcode == BUILT_IN_TM_LOAD_M128
350               || fcode == BUILT_IN_TM_LOAD_M256);
351     }
352   return false;
353 }
354
355 /* Return true if STMT is a TM store.  */
356
357 static bool
358 is_tm_store (gimple stmt)
359 {
360   tree fndecl;
361
362   if (gimple_code (stmt) != GIMPLE_CALL)
363     return false;
364
365   fndecl = gimple_call_fndecl (stmt);
366   return (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
367           && BUILTIN_TM_STORE_P (DECL_FUNCTION_CODE (fndecl)));
368 }
369
370 /* Same as above, but for simple TM stores, that is, not the
371    after-write, after-read, etc optimized variants.  */
372
373 static bool
374 is_tm_simple_store (gimple stmt)
375 {
376   tree fndecl;
377
378   if (gimple_code (stmt) != GIMPLE_CALL)
379     return false;
380
381   fndecl = gimple_call_fndecl (stmt);
382   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
383     {
384       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
385       return (fcode == BUILT_IN_TM_STORE_1
386               || fcode == BUILT_IN_TM_STORE_2
387               || fcode == BUILT_IN_TM_STORE_4
388               || fcode == BUILT_IN_TM_STORE_8
389               || fcode == BUILT_IN_TM_STORE_FLOAT
390               || fcode == BUILT_IN_TM_STORE_DOUBLE
391               || fcode == BUILT_IN_TM_STORE_LDOUBLE
392               || fcode == BUILT_IN_TM_STORE_M64
393               || fcode == BUILT_IN_TM_STORE_M128
394               || fcode == BUILT_IN_TM_STORE_M256);
395     }
396   return false;
397 }
398
399 /* Return true if FNDECL is BUILT_IN_TM_ABORT.  */
400
401 static bool
402 is_tm_abort (tree fndecl)
403 {
404   return (fndecl
405           && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
406           && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_TM_ABORT);
407 }
408
409 /* Build a GENERIC tree for a user abort.  This is called by front ends
410    while transforming the __tm_abort statement.  */
411
412 tree
413 build_tm_abort_call (location_t loc, bool is_outer)
414 {
415   return build_call_expr_loc (loc, builtin_decl_explicit (BUILT_IN_TM_ABORT), 1,
416                               build_int_cst (integer_type_node,
417                                              AR_USERABORT
418                                              | (is_outer ? AR_OUTERABORT : 0)));
419 }
420
421 /* Common gateing function for several of the TM passes.  */
422
423 static bool
424 gate_tm (void)
425 {
426   return flag_tm;
427 }
428 \f
429 /* Map for aribtrary function replacement under TM, as created
430    by the tm_wrap attribute.  */
431
432 static GTY((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
433      htab_t tm_wrap_map;
434
435 void
436 record_tm_replacement (tree from, tree to)
437 {
438   struct tree_map **slot, *h;
439
440   /* Do not inline wrapper functions that will get replaced in the TM
441      pass.
442
443      Suppose you have foo() that will get replaced into tmfoo().  Make
444      sure the inliner doesn't try to outsmart us and inline foo()
445      before we get a chance to do the TM replacement.  */
446   DECL_UNINLINABLE (from) = 1;
447
448   if (tm_wrap_map == NULL)
449     tm_wrap_map = htab_create_ggc (32, tree_map_hash, tree_map_eq, 0);
450
451   h = ggc_alloc_tree_map ();
452   h->hash = htab_hash_pointer (from);
453   h->base.from = from;
454   h->to = to;
455
456   slot = (struct tree_map **)
457     htab_find_slot_with_hash (tm_wrap_map, h, h->hash, INSERT);
458   *slot = h;
459 }
460
461 /* Return a TM-aware replacement function for DECL.  */
462
463 static tree
464 find_tm_replacement_function (tree fndecl)
465 {
466   if (tm_wrap_map)
467     {
468       struct tree_map *h, in;
469
470       in.base.from = fndecl;
471       in.hash = htab_hash_pointer (fndecl);
472       h = (struct tree_map *) htab_find_with_hash (tm_wrap_map, &in, in.hash);
473       if (h)
474         return h->to;
475     }
476
477   /* ??? We may well want TM versions of most of the common <string.h>
478      functions.  For now, we've already these two defined.  */
479   /* Adjust expand_call_tm() attributes as necessary for the cases
480      handled here:  */
481   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
482     switch (DECL_FUNCTION_CODE (fndecl))
483       {
484       case BUILT_IN_MEMCPY:
485         return builtin_decl_explicit (BUILT_IN_TM_MEMCPY);
486       case BUILT_IN_MEMMOVE:
487         return builtin_decl_explicit (BUILT_IN_TM_MEMMOVE);
488       case BUILT_IN_MEMSET:
489         return builtin_decl_explicit (BUILT_IN_TM_MEMSET);
490       default:
491         return NULL;
492       }
493
494   return NULL;
495 }
496
497 /* When appropriate, record TM replacement for memory allocation functions.
498
499    FROM is the FNDECL to wrap.  */
500 void
501 tm_malloc_replacement (tree from)
502 {
503   const char *str;
504   tree to;
505
506   if (TREE_CODE (from) != FUNCTION_DECL)
507     return;
508
509   /* If we have a previous replacement, the user must be explicitly
510      wrapping malloc/calloc/free.  They better know what they're
511      doing... */
512   if (find_tm_replacement_function (from))
513     return;
514
515   str = IDENTIFIER_POINTER (DECL_NAME (from));
516
517   if (!strcmp (str, "malloc"))
518     to = builtin_decl_explicit (BUILT_IN_TM_MALLOC);
519   else if (!strcmp (str, "calloc"))
520     to = builtin_decl_explicit (BUILT_IN_TM_CALLOC);
521   else if (!strcmp (str, "free"))
522     to = builtin_decl_explicit (BUILT_IN_TM_FREE);
523   else
524     return;
525
526   TREE_NOTHROW (to) = 0;
527
528   record_tm_replacement (from, to);
529 }
530 \f
531 /* Diagnostics for tm_safe functions/regions.  Called by the front end
532    once we've lowered the function to high-gimple.  */
533
534 /* Subroutine of diagnose_tm_safe_errors, called through walk_gimple_seq.
535    Process exactly one statement.  WI->INFO is set to non-null when in
536    the context of a tm_safe function, and null for a __transaction block.  */
537
538 #define DIAG_TM_OUTER           1
539 #define DIAG_TM_SAFE            2
540 #define DIAG_TM_RELAXED         4
541
542 struct diagnose_tm
543 {
544   unsigned int summary_flags : 8;
545   unsigned int block_flags : 8;
546   unsigned int func_flags : 8;
547   unsigned int saw_unsafe : 1;
548   unsigned int saw_volatile : 1;
549   gimple stmt;
550 };
551
552 /* Tree callback function for diagnose_tm pass.  */
553
554 static tree
555 diagnose_tm_1_op (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
556                   void *data)
557 {
558   struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
559   struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
560   enum tree_code code = TREE_CODE (*tp);
561
562   if ((code == VAR_DECL
563        || code == RESULT_DECL
564        || code == PARM_DECL)
565       && d->block_flags & (DIAG_TM_SAFE | DIAG_TM_RELAXED)
566       && TREE_THIS_VOLATILE (TREE_TYPE (*tp))
567       && !d->saw_volatile)
568     {
569       d->saw_volatile = 1;
570       error_at (gimple_location (d->stmt),
571                 "invalid volatile use of %qD inside transaction",
572                 *tp);
573     }
574
575   return NULL_TREE;
576 }
577
578 static tree
579 diagnose_tm_1 (gimple_stmt_iterator *gsi, bool *handled_ops_p,
580                     struct walk_stmt_info *wi)
581 {
582   gimple stmt = gsi_stmt (*gsi);
583   struct diagnose_tm *d = (struct diagnose_tm *) wi->info;
584
585   /* Save stmt for use in leaf analysis.  */
586   d->stmt = stmt;
587
588   switch (gimple_code (stmt))
589     {
590     case GIMPLE_CALL:
591       {
592         tree fn = gimple_call_fn (stmt);
593
594         if ((d->summary_flags & DIAG_TM_OUTER) == 0
595             && is_tm_may_cancel_outer (fn))
596           error_at (gimple_location (stmt),
597                     "%<transaction_may_cancel_outer%> function call not within"
598                     " outer transaction or %<transaction_may_cancel_outer%>");
599
600         if (d->summary_flags & DIAG_TM_SAFE)
601           {
602             bool is_safe, direct_call_p;
603             tree replacement;
604
605             if (TREE_CODE (fn) == ADDR_EXPR
606                 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
607               {
608                 direct_call_p = true;
609                 replacement = TREE_OPERAND (fn, 0);
610                 replacement = find_tm_replacement_function (replacement);
611                 if (replacement)
612                   fn = replacement;
613               }
614             else
615               {
616                 direct_call_p = false;
617                 replacement = NULL_TREE;
618               }
619
620             if (is_tm_safe_or_pure (fn))
621               is_safe = true;
622             else if (is_tm_callable (fn) || is_tm_irrevocable (fn))
623               {
624                 /* A function explicitly marked transaction_callable as
625                    opposed to transaction_safe is being defined to be
626                    unsafe as part of its ABI, regardless of its contents.  */
627                 is_safe = false;
628               }
629             else if (direct_call_p)
630               {
631                 if (flags_from_decl_or_type (fn) & ECF_TM_BUILTIN)
632                   is_safe = true;
633                 else if (replacement)
634                   {
635                     /* ??? At present we've been considering replacements
636                        merely transaction_callable, and therefore might
637                        enter irrevocable.  The tm_wrap attribute has not
638                        yet made it into the new language spec.  */
639                     is_safe = false;
640                   }
641                 else
642                   {
643                     /* ??? Diagnostics for unmarked direct calls moved into
644                        the IPA pass.  Section 3.2 of the spec details how
645                        functions not marked should be considered "implicitly
646                        safe" based on having examined the function body.  */
647                     is_safe = true;
648                   }
649               }
650             else
651               {
652                 /* An unmarked indirect call.  Consider it unsafe even
653                    though optimization may yet figure out how to inline.  */
654                 is_safe = false;
655               }
656
657             if (!is_safe)
658               {
659                 if (TREE_CODE (fn) == ADDR_EXPR)
660                   fn = TREE_OPERAND (fn, 0);
661                 if (d->block_flags & DIAG_TM_SAFE)
662                   {
663                     if (direct_call_p)
664                       error_at (gimple_location (stmt),
665                                 "unsafe function call %qD within "
666                                 "atomic transaction", fn);
667                     else
668                       error_at (gimple_location (stmt),
669                                 "unsafe function call %qE within "
670                                 "atomic transaction", fn);
671                   }
672                 else
673                   {
674                     if (direct_call_p)
675                       error_at (gimple_location (stmt),
676                                 "unsafe function call %qD within "
677                                 "%<transaction_safe%> function", fn);
678                     else
679                       error_at (gimple_location (stmt),
680                                 "unsafe function call %qE within "
681                                 "%<transaction_safe%> function", fn);
682                   }
683               }
684           }
685       }
686       break;
687
688     case GIMPLE_ASM:
689       /* ??? We ought to come up with a way to add attributes to
690          asm statements, and then add "transaction_safe" to it.
691          Either that or get the language spec to resurrect __tm_waiver.  */
692       if (d->block_flags & DIAG_TM_SAFE)
693         error_at (gimple_location (stmt),
694                   "asm not allowed in atomic transaction");
695       else if (d->func_flags & DIAG_TM_SAFE)
696         error_at (gimple_location (stmt),
697                   "asm not allowed in %<transaction_safe%> function");
698       else
699         d->saw_unsafe = true;
700       break;
701
702     case GIMPLE_TRANSACTION:
703       {
704         unsigned char inner_flags = DIAG_TM_SAFE;
705
706         if (gimple_transaction_subcode (stmt) & GTMA_IS_RELAXED)
707           {
708             if (d->block_flags & DIAG_TM_SAFE)
709               error_at (gimple_location (stmt),
710                         "relaxed transaction in atomic transaction");
711             else if (d->func_flags & DIAG_TM_SAFE)
712               error_at (gimple_location (stmt),
713                         "relaxed transaction in %<transaction_safe%> function");
714             else
715               d->saw_unsafe = true;
716             inner_flags = DIAG_TM_RELAXED;
717           }
718         else if (gimple_transaction_subcode (stmt) & GTMA_IS_OUTER)
719           {
720             if (d->block_flags)
721               error_at (gimple_location (stmt),
722                         "outer transaction in transaction");
723             else if (d->func_flags & DIAG_TM_OUTER)
724               error_at (gimple_location (stmt),
725                         "outer transaction in "
726                         "%<transaction_may_cancel_outer%> function");
727             else if (d->func_flags & DIAG_TM_SAFE)
728               error_at (gimple_location (stmt),
729                         "outer transaction in %<transaction_safe%> function");
730             else
731               d->saw_unsafe = true;
732             inner_flags |= DIAG_TM_OUTER;
733           }
734
735         *handled_ops_p = true;
736         if (gimple_transaction_body (stmt))
737           {
738             struct walk_stmt_info wi_inner;
739             struct diagnose_tm d_inner;
740
741             memset (&d_inner, 0, sizeof (d_inner));
742             d_inner.func_flags = d->func_flags;
743             d_inner.block_flags = d->block_flags | inner_flags;
744             d_inner.summary_flags = d_inner.func_flags | d_inner.block_flags;
745
746             memset (&wi_inner, 0, sizeof (wi_inner));
747             wi_inner.info = &d_inner;
748
749             walk_gimple_seq (gimple_transaction_body (stmt),
750                              diagnose_tm_1, diagnose_tm_1_op, &wi_inner);
751
752             d->saw_unsafe |= d_inner.saw_unsafe;
753           }
754       }
755       break;
756
757     default:
758       break;
759     }
760
761   return NULL_TREE;
762 }
763
764 static unsigned int
765 diagnose_tm_blocks (void)
766 {
767   struct walk_stmt_info wi;
768   struct diagnose_tm d;
769
770   memset (&d, 0, sizeof (d));
771   if (is_tm_may_cancel_outer (current_function_decl))
772     d.func_flags = DIAG_TM_OUTER | DIAG_TM_SAFE;
773   else if (is_tm_safe (current_function_decl))
774     d.func_flags = DIAG_TM_SAFE;
775   d.summary_flags = d.func_flags;
776
777   memset (&wi, 0, sizeof (wi));
778   wi.info = &d;
779
780   walk_gimple_seq (gimple_body (current_function_decl),
781                    diagnose_tm_1, diagnose_tm_1_op, &wi);
782
783   /* If we saw something other than a call that makes this function
784      unsafe, remember it so that the IPA pass only needs to scan calls.  */
785   if (d.saw_unsafe && !is_tm_safe_or_pure (current_function_decl))
786     cgraph_local_info (current_function_decl)->tm_may_enter_irr = 1;
787
788   return 0;
789 }
790
791 struct gimple_opt_pass pass_diagnose_tm_blocks =
792 {
793   {
794     GIMPLE_PASS,
795     "*diagnose_tm_blocks",              /* name */
796     gate_tm,                            /* gate */
797     diagnose_tm_blocks,                 /* execute */
798     NULL,                               /* sub */
799     NULL,                               /* next */
800     0,                                  /* static_pass_number */
801     TV_TRANS_MEM,                       /* tv_id */
802     PROP_gimple_any,                    /* properties_required */
803     0,                                  /* properties_provided */
804     0,                                  /* properties_destroyed */
805     0,                                  /* todo_flags_start */
806     0,                                  /* todo_flags_finish */
807   }
808 };
809 \f
810 /* Instead of instrumenting thread private memory, we save the
811    addresses in a log which we later use to save/restore the addresses
812    upon transaction start/restart.
813
814    The log is keyed by address, where each element contains individual
815    statements among different code paths that perform the store.
816
817    This log is later used to generate either plain save/restore of the
818    addresses upon transaction start/restart, or calls to the ITM_L*
819    logging functions.
820
821    So for something like:
822
823        struct large { int x[1000]; };
824        struct large lala = { 0 };
825        __transaction {
826          lala.x[i] = 123;
827          ...
828        }
829
830    We can either save/restore:
831
832        lala = { 0 };
833        trxn = _ITM_startTransaction ();
834        if (trxn & a_saveLiveVariables)
835          tmp_lala1 = lala.x[i];
836        else if (a & a_restoreLiveVariables)
837          lala.x[i] = tmp_lala1;
838
839    or use the logging functions:
840
841        lala = { 0 };
842        trxn = _ITM_startTransaction ();
843        _ITM_LU4 (&lala.x[i]);
844
845    Obviously, if we use _ITM_L* to log, we prefer to call _ITM_L* as
846    far up the dominator tree to shadow all of the writes to a given
847    location (thus reducing the total number of logging calls), but not
848    so high as to be called on a path that does not perform a
849    write.  */
850
851 /* One individual log entry.  We may have multiple statements for the
852    same location if neither dominate each other (on different
853    execution paths).  */
854 typedef struct tm_log_entry
855 {
856   /* Address to save.  */
857   tree addr;
858   /* Entry block for the transaction this address occurs in.  */
859   basic_block entry_block;
860   /* Dominating statements the store occurs in.  */
861   gimple_vec stmts;
862   /* Initially, while we are building the log, we place a nonzero
863      value here to mean that this address *will* be saved with a
864      save/restore sequence.  Later, when generating the save sequence
865      we place the SSA temp generated here.  */
866   tree save_var;
867 } *tm_log_entry_t;
868
869 /* The actual log.  */
870 static htab_t tm_log;
871
872 /* Addresses to log with a save/restore sequence.  These should be in
873    dominator order.  */
874 static VEC(tree,heap) *tm_log_save_addresses;
875
876 /* Map for an SSA_NAME originally pointing to a non aliased new piece
877    of memory (malloc, alloc, etc).  */
878 static htab_t tm_new_mem_hash;
879
880 enum thread_memory_type
881   {
882     mem_non_local = 0,
883     mem_thread_local,
884     mem_transaction_local,
885     mem_max
886   };
887
888 typedef struct tm_new_mem_map
889 {
890   /* SSA_NAME being dereferenced.  */
891   tree val;
892   enum thread_memory_type local_new_memory;
893 } tm_new_mem_map_t;
894
895 /* Htab support.  Return hash value for a `tm_log_entry'.  */
896 static hashval_t
897 tm_log_hash (const void *p)
898 {
899   const struct tm_log_entry *log = (const struct tm_log_entry *) p;
900   return iterative_hash_expr (log->addr, 0);
901 }
902
903 /* Htab support.  Return true if two log entries are the same.  */
904 static int
905 tm_log_eq (const void *p1, const void *p2)
906 {
907   const struct tm_log_entry *log1 = (const struct tm_log_entry *) p1;
908   const struct tm_log_entry *log2 = (const struct tm_log_entry *) p2;
909
910   /* FIXME:
911
912      rth: I suggest that we get rid of the component refs etc.
913      I.e. resolve the reference to base + offset.
914
915      We may need to actually finish a merge with mainline for this,
916      since we'd like to be presented with Richi's MEM_REF_EXPRs more
917      often than not.  But in the meantime your tm_log_entry could save
918      the results of get_inner_reference.
919
920      See: g++.dg/tm/pr46653.C
921   */
922
923   /* Special case plain equality because operand_equal_p() below will
924      return FALSE if the addresses are equal but they have
925      side-effects (e.g. a volatile address).  */
926   if (log1->addr == log2->addr)
927     return true;
928
929   return operand_equal_p (log1->addr, log2->addr, 0);
930 }
931
932 /* Htab support.  Free one tm_log_entry.  */
933 static void
934 tm_log_free (void *p)
935 {
936   struct tm_log_entry *lp = (struct tm_log_entry *) p;
937   VEC_free (gimple, heap, lp->stmts);
938   free (lp);
939 }
940
941 /* Initialize logging data structures.  */
942 static void
943 tm_log_init (void)
944 {
945   tm_log = htab_create (10, tm_log_hash, tm_log_eq, tm_log_free);
946   tm_new_mem_hash = htab_create (5, struct_ptr_hash, struct_ptr_eq, free);
947   tm_log_save_addresses = VEC_alloc (tree, heap, 5);
948 }
949
950 /* Free logging data structures.  */
951 static void
952 tm_log_delete (void)
953 {
954   htab_delete (tm_log);
955   htab_delete (tm_new_mem_hash);
956   VEC_free (tree, heap, tm_log_save_addresses);
957 }
958
959 /* Return true if MEM is a transaction invariant memory for the TM
960    region starting at REGION_ENTRY_BLOCK.  */
961 static bool
962 transaction_invariant_address_p (const_tree mem, basic_block region_entry_block)
963 {
964   if ((TREE_CODE (mem) == INDIRECT_REF || TREE_CODE (mem) == MEM_REF)
965       && TREE_CODE (TREE_OPERAND (mem, 0)) == SSA_NAME)
966     {
967       basic_block def_bb;
968
969       def_bb = gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (mem, 0)));
970       return def_bb != region_entry_block
971         && dominated_by_p (CDI_DOMINATORS, region_entry_block, def_bb);
972     }
973
974   mem = strip_invariant_refs (mem);
975   return mem && (CONSTANT_CLASS_P (mem) || decl_address_invariant_p (mem));
976 }
977
978 /* Given an address ADDR in STMT, find it in the memory log or add it,
979    making sure to keep only the addresses highest in the dominator
980    tree.
981
982    ENTRY_BLOCK is the entry_block for the transaction.
983
984    If we find the address in the log, make sure it's either the same
985    address, or an equivalent one that dominates ADDR.
986
987    If we find the address, but neither ADDR dominates the found
988    address, nor the found one dominates ADDR, we're on different
989    execution paths.  Add it.
990
991    If known, ENTRY_BLOCK is the entry block for the region, otherwise
992    NULL.  */
993 static void
994 tm_log_add (basic_block entry_block, tree addr, gimple stmt)
995 {
996   void **slot;
997   struct tm_log_entry l, *lp;
998
999   l.addr = addr;
1000   slot = htab_find_slot (tm_log, &l, INSERT);
1001   if (!*slot)
1002     {
1003       tree type = TREE_TYPE (addr);
1004
1005       lp = XNEW (struct tm_log_entry);
1006       lp->addr = addr;
1007       *slot = lp;
1008
1009       /* Small invariant addresses can be handled as save/restores.  */
1010       if (entry_block
1011           && transaction_invariant_address_p (lp->addr, entry_block)
1012           && TYPE_SIZE_UNIT (type) != NULL
1013           && host_integerp (TYPE_SIZE_UNIT (type), 1)
1014           && (tree_low_cst (TYPE_SIZE_UNIT (type), 1)
1015               < PARAM_VALUE (PARAM_TM_MAX_AGGREGATE_SIZE))
1016           /* We must be able to copy this type normally.  I.e., no
1017              special constructors and the like.  */
1018           && !TREE_ADDRESSABLE (type))
1019         {
1020           lp->save_var = create_tmp_var (TREE_TYPE (lp->addr), "tm_save");
1021           add_referenced_var (lp->save_var);
1022           lp->stmts = NULL;
1023           lp->entry_block = entry_block;
1024           /* Save addresses separately in dominator order so we don't
1025              get confused by overlapping addresses in the save/restore
1026              sequence.  */
1027           VEC_safe_push (tree, heap, tm_log_save_addresses, lp->addr);
1028         }
1029       else
1030         {
1031           /* Use the logging functions.  */
1032           lp->stmts = VEC_alloc (gimple, heap, 5);
1033           VEC_quick_push (gimple, lp->stmts, stmt);
1034           lp->save_var = NULL;
1035         }
1036     }
1037   else
1038     {
1039       size_t i;
1040       gimple oldstmt;
1041
1042       lp = (struct tm_log_entry *) *slot;
1043
1044       /* If we're generating a save/restore sequence, we don't care
1045          about statements.  */
1046       if (lp->save_var)
1047         return;
1048
1049       for (i = 0; VEC_iterate (gimple, lp->stmts, i, oldstmt); ++i)
1050         {
1051           if (stmt == oldstmt)
1052             return;
1053           /* We already have a store to the same address, higher up the
1054              dominator tree.  Nothing to do.  */
1055           if (dominated_by_p (CDI_DOMINATORS,
1056                               gimple_bb (stmt), gimple_bb (oldstmt)))
1057             return;
1058           /* We should be processing blocks in dominator tree order.  */
1059           gcc_assert (!dominated_by_p (CDI_DOMINATORS,
1060                                        gimple_bb (oldstmt), gimple_bb (stmt)));
1061         }
1062       /* Store is on a different code path.  */
1063       VEC_safe_push (gimple, heap, lp->stmts, stmt);
1064     }
1065 }
1066
1067 /* Gimplify the address of a TARGET_MEM_REF.  Return the SSA_NAME
1068    result, insert the new statements before GSI.  */
1069
1070 static tree
1071 gimplify_addr (gimple_stmt_iterator *gsi, tree x)
1072 {
1073   if (TREE_CODE (x) == TARGET_MEM_REF)
1074     x = tree_mem_ref_addr (build_pointer_type (TREE_TYPE (x)), x);
1075   else
1076     x = build_fold_addr_expr (x);
1077   return force_gimple_operand_gsi (gsi, x, true, NULL, true, GSI_SAME_STMT);
1078 }
1079
1080 /* Instrument one address with the logging functions.
1081    ADDR is the address to save.
1082    STMT is the statement before which to place it.  */
1083 static void
1084 tm_log_emit_stmt (tree addr, gimple stmt)
1085 {
1086   tree type = TREE_TYPE (addr);
1087   tree size = TYPE_SIZE_UNIT (type);
1088   gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1089   gimple log;
1090   enum built_in_function code = BUILT_IN_TM_LOG;
1091
1092   if (type == float_type_node)
1093     code = BUILT_IN_TM_LOG_FLOAT;
1094   else if (type == double_type_node)
1095     code = BUILT_IN_TM_LOG_DOUBLE;
1096   else if (type == long_double_type_node)
1097     code = BUILT_IN_TM_LOG_LDOUBLE;
1098   else if (host_integerp (size, 1))
1099     {
1100       unsigned int n = tree_low_cst (size, 1);
1101       switch (n)
1102         {
1103         case 1:
1104           code = BUILT_IN_TM_LOG_1;
1105           break;
1106         case 2:
1107           code = BUILT_IN_TM_LOG_2;
1108           break;
1109         case 4:
1110           code = BUILT_IN_TM_LOG_4;
1111           break;
1112         case 8:
1113           code = BUILT_IN_TM_LOG_8;
1114           break;
1115         default:
1116           code = BUILT_IN_TM_LOG;
1117           if (TREE_CODE (type) == VECTOR_TYPE)
1118             {
1119               if (n == 8 && builtin_decl_explicit (BUILT_IN_TM_LOG_M64))
1120                 code = BUILT_IN_TM_LOG_M64;
1121               else if (n == 16 && builtin_decl_explicit (BUILT_IN_TM_LOG_M128))
1122                 code = BUILT_IN_TM_LOG_M128;
1123               else if (n == 32 && builtin_decl_explicit (BUILT_IN_TM_LOG_M256))
1124                 code = BUILT_IN_TM_LOG_M256;
1125             }
1126           break;
1127         }
1128     }
1129
1130   addr = gimplify_addr (&gsi, addr);
1131   if (code == BUILT_IN_TM_LOG)
1132     log = gimple_build_call (builtin_decl_explicit (code), 2, addr,  size);
1133   else
1134     log = gimple_build_call (builtin_decl_explicit (code), 1, addr);
1135   gsi_insert_before (&gsi, log, GSI_SAME_STMT);
1136 }
1137
1138 /* Go through the log and instrument address that must be instrumented
1139    with the logging functions.  Leave the save/restore addresses for
1140    later.  */
1141 static void
1142 tm_log_emit (void)
1143 {
1144   htab_iterator hi;
1145   struct tm_log_entry *lp;
1146
1147   FOR_EACH_HTAB_ELEMENT (tm_log, lp, tm_log_entry_t, hi)
1148     {
1149       size_t i;
1150       gimple stmt;
1151
1152       if (dump_file)
1153         {
1154           fprintf (dump_file, "TM thread private mem logging: ");
1155           print_generic_expr (dump_file, lp->addr, 0);
1156           fprintf (dump_file, "\n");
1157         }
1158
1159       if (lp->save_var)
1160         {
1161           if (dump_file)
1162             fprintf (dump_file, "DUMPING to variable\n");
1163           continue;
1164         }
1165       else
1166         {
1167           if (dump_file)
1168             fprintf (dump_file, "DUMPING with logging functions\n");
1169           for (i = 0; VEC_iterate (gimple, lp->stmts, i, stmt); ++i)
1170             tm_log_emit_stmt (lp->addr, stmt);
1171         }
1172     }
1173 }
1174
1175 /* Emit the save sequence for the corresponding addresses in the log.
1176    ENTRY_BLOCK is the entry block for the transaction.
1177    BB is the basic block to insert the code in.  */
1178 static void
1179 tm_log_emit_saves (basic_block entry_block, basic_block bb)
1180 {
1181   size_t i;
1182   gimple_stmt_iterator gsi = gsi_last_bb (bb);
1183   gimple stmt;
1184   struct tm_log_entry l, *lp;
1185
1186   for (i = 0; i < VEC_length (tree, tm_log_save_addresses); ++i)
1187     {
1188       l.addr = VEC_index (tree, tm_log_save_addresses, i);
1189       lp = (struct tm_log_entry *) *htab_find_slot (tm_log, &l, NO_INSERT);
1190       gcc_assert (lp->save_var != NULL);
1191
1192       /* We only care about variables in the current transaction.  */
1193       if (lp->entry_block != entry_block)
1194         continue;
1195
1196       stmt = gimple_build_assign (lp->save_var, unshare_expr (lp->addr));
1197
1198       /* Make sure we can create an SSA_NAME for this type.  For
1199          instance, aggregates aren't allowed, in which case the system
1200          will create a VOP for us and everything will just work.  */
1201       if (is_gimple_reg_type (TREE_TYPE (lp->save_var)))
1202         {
1203           lp->save_var = make_ssa_name (lp->save_var, stmt);
1204           gimple_assign_set_lhs (stmt, lp->save_var);
1205         }
1206
1207       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1208     }
1209 }
1210
1211 /* Emit the restore sequence for the corresponding addresses in the log.
1212    ENTRY_BLOCK is the entry block for the transaction.
1213    BB is the basic block to insert the code in.  */
1214 static void
1215 tm_log_emit_restores (basic_block entry_block, basic_block bb)
1216 {
1217   int i;
1218   struct tm_log_entry l, *lp;
1219   gimple_stmt_iterator gsi;
1220   gimple stmt;
1221
1222   for (i = VEC_length (tree, tm_log_save_addresses) - 1; i >= 0; i--)
1223     {
1224       l.addr = VEC_index (tree, tm_log_save_addresses, i);
1225       lp = (struct tm_log_entry *) *htab_find_slot (tm_log, &l, NO_INSERT);
1226       gcc_assert (lp->save_var != NULL);
1227
1228       /* We only care about variables in the current transaction.  */
1229       if (lp->entry_block != entry_block)
1230         continue;
1231
1232       /* Restores are in LIFO order from the saves in case we have
1233          overlaps.  */
1234       gsi = gsi_start_bb (bb);
1235
1236       stmt = gimple_build_assign (unshare_expr (lp->addr), lp->save_var);
1237       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1238     }
1239 }
1240
1241 /* Emit the checks for performing either a save or a restore sequence.
1242
1243    TRXN_PROP is either A_SAVELIVEVARIABLES or A_RESTORELIVEVARIABLES.
1244
1245    The code sequence is inserted in a new basic block created in
1246    END_BB which is inserted between BEFORE_BB and the destination of
1247    FALLTHRU_EDGE.
1248
1249    STATUS is the return value from _ITM_beginTransaction.
1250    ENTRY_BLOCK is the entry block for the transaction.
1251    EMITF is a callback to emit the actual save/restore code.
1252
1253    The basic block containing the conditional checking for TRXN_PROP
1254    is returned.  */
1255 static basic_block
1256 tm_log_emit_save_or_restores (basic_block entry_block,
1257                               unsigned trxn_prop,
1258                               tree status,
1259                               void (*emitf)(basic_block, basic_block),
1260                               basic_block before_bb,
1261                               edge fallthru_edge,
1262                               basic_block *end_bb)
1263 {
1264   basic_block cond_bb, code_bb;
1265   gimple cond_stmt, stmt;
1266   gimple_stmt_iterator gsi;
1267   tree t1, t2;
1268   int old_flags = fallthru_edge->flags;
1269
1270   cond_bb = create_empty_bb (before_bb);
1271   code_bb = create_empty_bb (cond_bb);
1272   *end_bb = create_empty_bb (code_bb);
1273   redirect_edge_pred (fallthru_edge, *end_bb);
1274   fallthru_edge->flags = EDGE_FALLTHRU;
1275   make_edge (before_bb, cond_bb, old_flags);
1276
1277   set_immediate_dominator (CDI_DOMINATORS, cond_bb, before_bb);
1278   set_immediate_dominator (CDI_DOMINATORS, code_bb, cond_bb);
1279
1280   gsi = gsi_last_bb (cond_bb);
1281
1282   /* t1 = status & A_{property}.  */
1283   t1 = make_rename_temp (TREE_TYPE (status), NULL);
1284   t2 = build_int_cst (TREE_TYPE (status), trxn_prop);
1285   stmt = gimple_build_assign_with_ops (BIT_AND_EXPR, t1, status, t2);
1286   gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1287
1288   /* if (t1).  */
1289   t2 = build_int_cst (TREE_TYPE (status), 0);
1290   cond_stmt = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
1291   gsi_insert_after (&gsi, cond_stmt, GSI_CONTINUE_LINKING);
1292
1293   emitf (entry_block, code_bb);
1294
1295   make_edge (cond_bb, code_bb, EDGE_TRUE_VALUE);
1296   make_edge (cond_bb, *end_bb, EDGE_FALSE_VALUE);
1297   make_edge (code_bb, *end_bb, EDGE_FALLTHRU);
1298
1299   return cond_bb;
1300 }
1301 \f
1302 static tree lower_sequence_tm (gimple_stmt_iterator *, bool *,
1303                                struct walk_stmt_info *);
1304 static tree lower_sequence_no_tm (gimple_stmt_iterator *, bool *,
1305                                   struct walk_stmt_info *);
1306
1307 /* Evaluate an address X being dereferenced and determine if it
1308    originally points to a non aliased new chunk of memory (malloc,
1309    alloca, etc).
1310
1311    Return MEM_THREAD_LOCAL if it points to a thread-local address.
1312    Return MEM_TRANSACTION_LOCAL if it points to a transaction-local address.
1313    Return MEM_NON_LOCAL otherwise.
1314
1315    ENTRY_BLOCK is the entry block to the transaction containing the
1316    dereference of X.  */
1317 static enum thread_memory_type
1318 thread_private_new_memory (basic_block entry_block, tree x)
1319 {
1320   gimple stmt = NULL;
1321   enum tree_code code;
1322   void **slot;
1323   tm_new_mem_map_t elt, *elt_p;
1324   tree val = x;
1325   enum thread_memory_type retval = mem_transaction_local;
1326
1327   if (!entry_block
1328       || TREE_CODE (x) != SSA_NAME
1329       /* Possible uninitialized use, or a function argument.  In
1330          either case, we don't care.  */
1331       || SSA_NAME_IS_DEFAULT_DEF (x))
1332     return mem_non_local;
1333
1334   /* Look in cache first.  */
1335   elt.val = x;
1336   slot = htab_find_slot (tm_new_mem_hash, &elt, INSERT);
1337   elt_p = (tm_new_mem_map_t *) *slot;
1338   if (elt_p)
1339     return elt_p->local_new_memory;
1340
1341   /* Optimistically assume the memory is transaction local during
1342      processing.  This catches recursion into this variable.  */
1343   *slot = elt_p = XNEW (tm_new_mem_map_t);
1344   elt_p->val = val;
1345   elt_p->local_new_memory = mem_transaction_local;
1346
1347   /* Search DEF chain to find the original definition of this address.  */
1348   do
1349     {
1350       if (ptr_deref_may_alias_global_p (x))
1351         {
1352           /* Address escapes.  This is not thread-private.  */
1353           retval = mem_non_local;
1354           goto new_memory_ret;
1355         }
1356
1357       stmt = SSA_NAME_DEF_STMT (x);
1358
1359       /* If the malloc call is outside the transaction, this is
1360          thread-local.  */
1361       if (retval != mem_thread_local
1362           && !dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt), entry_block))
1363         retval = mem_thread_local;
1364
1365       if (is_gimple_assign (stmt))
1366         {
1367           code = gimple_assign_rhs_code (stmt);
1368           /* x = foo ==> foo */
1369           if (code == SSA_NAME)
1370             x = gimple_assign_rhs1 (stmt);
1371           /* x = foo + n ==> foo */
1372           else if (code == POINTER_PLUS_EXPR)
1373             x = gimple_assign_rhs1 (stmt);
1374           /* x = (cast*) foo ==> foo */
1375           else if (code == VIEW_CONVERT_EXPR || code == NOP_EXPR)
1376             x = gimple_assign_rhs1 (stmt);
1377           else
1378             {
1379               retval = mem_non_local;
1380               goto new_memory_ret;
1381             }
1382         }
1383       else
1384         {
1385           if (gimple_code (stmt) == GIMPLE_PHI)
1386             {
1387               unsigned int i;
1388               enum thread_memory_type mem;
1389               tree phi_result = gimple_phi_result (stmt);
1390
1391               /* If any of the ancestors are non-local, we are sure to
1392                  be non-local.  Otherwise we can avoid doing anything
1393                  and inherit what has already been generated.  */
1394               retval = mem_max;
1395               for (i = 0; i < gimple_phi_num_args (stmt); ++i)
1396                 {
1397                   tree op = PHI_ARG_DEF (stmt, i);
1398
1399                   /* Exclude self-assignment.  */
1400                   if (phi_result == op)
1401                     continue;
1402
1403                   mem = thread_private_new_memory (entry_block, op);
1404                   if (mem == mem_non_local)
1405                     {
1406                       retval = mem;
1407                       goto new_memory_ret;
1408                     }
1409                   retval = MIN (retval, mem);
1410                 }
1411               goto new_memory_ret;
1412             }
1413           break;
1414         }
1415     }
1416   while (TREE_CODE (x) == SSA_NAME);
1417
1418   if (stmt && is_gimple_call (stmt) && gimple_call_flags (stmt) & ECF_MALLOC)
1419     /* Thread-local or transaction-local.  */
1420     ;
1421   else
1422     retval = mem_non_local;
1423
1424  new_memory_ret:
1425   elt_p->local_new_memory = retval;
1426   return retval;
1427 }
1428
1429 /* Determine whether X has to be instrumented using a read
1430    or write barrier.
1431
1432    ENTRY_BLOCK is the entry block for the region where stmt resides
1433    in.  NULL if unknown.
1434
1435    STMT is the statement in which X occurs in.  It is used for thread
1436    private memory instrumentation.  If no TPM instrumentation is
1437    desired, STMT should be null.  */
1438 static bool
1439 requires_barrier (basic_block entry_block, tree x, gimple stmt)
1440 {
1441   tree orig = x;
1442   while (handled_component_p (x))
1443     x = TREE_OPERAND (x, 0);
1444
1445   switch (TREE_CODE (x))
1446     {
1447     case INDIRECT_REF:
1448     case MEM_REF:
1449       {
1450         enum thread_memory_type ret;
1451
1452         ret = thread_private_new_memory (entry_block, TREE_OPERAND (x, 0));
1453         if (ret == mem_non_local)
1454           return true;
1455         if (stmt && ret == mem_thread_local)
1456           /* ?? Should we pass `orig', or the INDIRECT_REF X.  ?? */
1457           tm_log_add (entry_block, orig, stmt);
1458
1459         /* Transaction-locals require nothing at all.  For malloc, a
1460            transaction restart frees the memory and we reallocate.
1461            For alloca, the stack pointer gets reset by the retry and
1462            we reallocate.  */
1463         return false;
1464       }
1465
1466     case TARGET_MEM_REF:
1467       if (TREE_CODE (TMR_BASE (x)) != ADDR_EXPR)
1468         return true;
1469       x = TREE_OPERAND (TMR_BASE (x), 0);
1470       if (TREE_CODE (x) == PARM_DECL)
1471         return false;
1472       gcc_assert (TREE_CODE (x) == VAR_DECL);
1473       /* FALLTHRU */
1474
1475     case PARM_DECL:
1476     case RESULT_DECL:
1477     case VAR_DECL:
1478       if (DECL_BY_REFERENCE (x))
1479         {
1480           /* ??? This value is a pointer, but aggregate_value_p has been
1481              jigged to return true which confuses needs_to_live_in_memory.
1482              This ought to be cleaned up generically.
1483
1484              FIXME: Verify this still happens after the next mainline
1485              merge.  Testcase ie g++.dg/tm/pr47554.C.
1486           */
1487           return false;
1488         }
1489
1490       if (is_global_var (x))
1491         return !TREE_READONLY (x);
1492       if (/* FIXME: This condition should actually go below in the
1493              tm_log_add() call, however is_call_clobbered() depends on
1494              aliasing info which is not available during
1495              gimplification.  Since requires_barrier() gets called
1496              during lower_sequence_tm/gimplification, leave the call
1497              to needs_to_live_in_memory until we eliminate
1498              lower_sequence_tm altogether.  */
1499           needs_to_live_in_memory (x)
1500           /* X escapes.  */
1501           || ptr_deref_may_alias_global_p (x))
1502         return true;
1503       else
1504         {
1505           /* For local memory that doesn't escape (aka thread private
1506              memory), we can either save the value at the beginning of
1507              the transaction and restore on restart, or call a tm
1508              function to dynamically save and restore on restart
1509              (ITM_L*).  */
1510           if (stmt)
1511             tm_log_add (entry_block, orig, stmt);
1512           return false;
1513         }
1514
1515     default:
1516       return false;
1517     }
1518 }
1519
1520 /* Mark the GIMPLE_ASSIGN statement as appropriate for being inside
1521    a transaction region.  */
1522
1523 static void
1524 examine_assign_tm (unsigned *state, gimple_stmt_iterator *gsi)
1525 {
1526   gimple stmt = gsi_stmt (*gsi);
1527
1528   if (requires_barrier (/*entry_block=*/NULL, gimple_assign_rhs1 (stmt), NULL))
1529     *state |= GTMA_HAVE_LOAD;
1530   if (requires_barrier (/*entry_block=*/NULL, gimple_assign_lhs (stmt), NULL))
1531     *state |= GTMA_HAVE_STORE;
1532 }
1533
1534 /* Mark a GIMPLE_CALL as appropriate for being inside a transaction.  */
1535
1536 static void
1537 examine_call_tm (unsigned *state, gimple_stmt_iterator *gsi)
1538 {
1539   gimple stmt = gsi_stmt (*gsi);
1540   tree fn;
1541
1542   if (is_tm_pure_call (stmt))
1543     return;
1544
1545   /* Check if this call is a transaction abort.  */
1546   fn = gimple_call_fndecl (stmt);
1547   if (is_tm_abort (fn))
1548     *state |= GTMA_HAVE_ABORT;
1549
1550   /* Note that something may happen.  */
1551   *state |= GTMA_HAVE_LOAD | GTMA_HAVE_STORE;
1552 }
1553
1554 /* Lower a GIMPLE_TRANSACTION statement.  */
1555
1556 static void
1557 lower_transaction (gimple_stmt_iterator *gsi, struct walk_stmt_info *wi)
1558 {
1559   gimple g, stmt = gsi_stmt (*gsi);
1560   unsigned int *outer_state = (unsigned int *) wi->info;
1561   unsigned int this_state = 0;
1562   struct walk_stmt_info this_wi;
1563
1564   /* First, lower the body.  The scanning that we do inside gives
1565      us some idea of what we're dealing with.  */
1566   memset (&this_wi, 0, sizeof (this_wi));
1567   this_wi.info = (void *) &this_state;
1568   walk_gimple_seq (gimple_transaction_body (stmt),
1569                    lower_sequence_tm, NULL, &this_wi);
1570
1571   /* If there was absolutely nothing transaction related inside the
1572      transaction, we may elide it.  Likewise if this is a nested
1573      transaction and does not contain an abort.  */
1574   if (this_state == 0
1575       || (!(this_state & GTMA_HAVE_ABORT) && outer_state != NULL))
1576     {
1577       if (outer_state)
1578         *outer_state |= this_state;
1579
1580       gsi_insert_seq_before (gsi, gimple_transaction_body (stmt),
1581                              GSI_SAME_STMT);
1582       gimple_transaction_set_body (stmt, NULL);
1583
1584       gsi_remove (gsi, true);
1585       wi->removed_stmt = true;
1586       return;
1587     }
1588
1589   /* Wrap the body of the transaction in a try-finally node so that
1590      the commit call is always properly called.  */
1591   g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT), 0);
1592   if (flag_exceptions)
1593     {
1594       tree ptr;
1595       gimple_seq n_seq, e_seq;
1596
1597       n_seq = gimple_seq_alloc_with_stmt (g);
1598       e_seq = gimple_seq_alloc ();
1599
1600       g = gimple_build_call (builtin_decl_explicit (BUILT_IN_EH_POINTER),
1601                              1, integer_zero_node);
1602       ptr = create_tmp_var (ptr_type_node, NULL);
1603       gimple_call_set_lhs (g, ptr);
1604       gimple_seq_add_stmt (&e_seq, g);
1605
1606       g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_COMMIT_EH),
1607                              1, ptr);
1608       gimple_seq_add_stmt (&e_seq, g);
1609
1610       g = gimple_build_eh_else (n_seq, e_seq);
1611     }
1612
1613   g = gimple_build_try (gimple_transaction_body (stmt),
1614                         gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_FINALLY);
1615   gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
1616
1617   gimple_transaction_set_body (stmt, NULL);
1618
1619   /* If the transaction calls abort or if this is an outer transaction,
1620      add an "over" label afterwards.  */
1621   if ((this_state & (GTMA_HAVE_ABORT))
1622       || (gimple_transaction_subcode(stmt) & GTMA_IS_OUTER))
1623     {
1624       tree label = create_artificial_label (UNKNOWN_LOCATION);
1625       gimple_transaction_set_label (stmt, label);
1626       gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
1627     }
1628
1629   /* Record the set of operations found for use later.  */
1630   this_state |= gimple_transaction_subcode (stmt) & GTMA_DECLARATION_MASK;
1631   gimple_transaction_set_subcode (stmt, this_state);
1632 }
1633
1634 /* Iterate through the statements in the sequence, lowering them all
1635    as appropriate for being in a transaction.  */
1636
1637 static tree
1638 lower_sequence_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1639                    struct walk_stmt_info *wi)
1640 {
1641   unsigned int *state = (unsigned int *) wi->info;
1642   gimple stmt = gsi_stmt (*gsi);
1643
1644   *handled_ops_p = true;
1645   switch (gimple_code (stmt))
1646     {
1647     case GIMPLE_ASSIGN:
1648       /* Only memory reads/writes need to be instrumented.  */
1649       if (gimple_assign_single_p (stmt))
1650         examine_assign_tm (state, gsi);
1651       break;
1652
1653     case GIMPLE_CALL:
1654       examine_call_tm (state, gsi);
1655       break;
1656
1657     case GIMPLE_ASM:
1658       *state |= GTMA_MAY_ENTER_IRREVOCABLE;
1659       break;
1660
1661     case GIMPLE_TRANSACTION:
1662       lower_transaction (gsi, wi);
1663       break;
1664
1665     default:
1666       *handled_ops_p = !gimple_has_substatements (stmt);
1667       break;
1668     }
1669
1670   return NULL_TREE;
1671 }
1672
1673 /* Iterate through the statements in the sequence, lowering them all
1674    as appropriate for being outside of a transaction.  */
1675
1676 static tree
1677 lower_sequence_no_tm (gimple_stmt_iterator *gsi, bool *handled_ops_p,
1678                       struct walk_stmt_info * wi)
1679 {
1680   gimple stmt = gsi_stmt (*gsi);
1681
1682   if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1683     {
1684       *handled_ops_p = true;
1685       lower_transaction (gsi, wi);
1686     }
1687   else
1688     *handled_ops_p = !gimple_has_substatements (stmt);
1689
1690   return NULL_TREE;
1691 }
1692
1693 /* Main entry point for flattening GIMPLE_TRANSACTION constructs.  After
1694    this, GIMPLE_TRANSACTION nodes still exist, but the nested body has
1695    been moved out, and all the data required for constructing a proper
1696    CFG has been recorded.  */
1697
1698 static unsigned int
1699 execute_lower_tm (void)
1700 {
1701   struct walk_stmt_info wi;
1702
1703   /* Transactional clones aren't created until a later pass.  */
1704   gcc_assert (!decl_is_tm_clone (current_function_decl));
1705
1706   memset (&wi, 0, sizeof (wi));
1707   walk_gimple_seq (gimple_body (current_function_decl),
1708                    lower_sequence_no_tm, NULL, &wi);
1709
1710   return 0;
1711 }
1712
1713 struct gimple_opt_pass pass_lower_tm =
1714 {
1715  {
1716   GIMPLE_PASS,
1717   "tmlower",                            /* name */
1718   gate_tm,                              /* gate */
1719   execute_lower_tm,                     /* execute */
1720   NULL,                                 /* sub */
1721   NULL,                                 /* next */
1722   0,                                    /* static_pass_number */
1723   TV_TRANS_MEM,                         /* tv_id */
1724   PROP_gimple_lcf,                      /* properties_required */
1725   0,                                    /* properties_provided */
1726   0,                                    /* properties_destroyed */
1727   0,                                    /* todo_flags_start */
1728   TODO_dump_func                        /* todo_flags_finish */
1729  }
1730 };
1731 \f
1732 /* Collect region information for each transaction.  */
1733
1734 struct tm_region
1735 {
1736   /* Link to the next unnested transaction.  */
1737   struct tm_region *next;
1738
1739   /* Link to the next inner transaction.  */
1740   struct tm_region *inner;
1741
1742   /* Link to the next outer transaction.  */
1743   struct tm_region *outer;
1744
1745   /* The GIMPLE_TRANSACTION statement beginning this transaction.  */
1746   gimple transaction_stmt;
1747
1748   /* The entry block to this region.  */
1749   basic_block entry_block;
1750
1751   /* The set of all blocks that end the region; NULL if only EXIT_BLOCK.
1752      These blocks are still a part of the region (i.e., the border is
1753      inclusive). Note that this set is only complete for paths in the CFG
1754      starting at ENTRY_BLOCK, and that there is no exit block recorded for
1755      the edge to the "over" label.  */
1756   bitmap exit_blocks;
1757
1758   /* The set of all blocks that have an TM_IRREVOCABLE call.  */
1759   bitmap irr_blocks;
1760 };
1761
1762 /* True if there are pending edge statements to be committed for the
1763    current function being scanned in the tmmark pass.  */
1764 bool pending_edge_inserts_p;
1765
1766 static struct tm_region *all_tm_regions;
1767 static bitmap_obstack tm_obstack;
1768
1769
1770 /* A subroutine of tm_region_init.  Record the existance of the
1771    GIMPLE_TRANSACTION statement in a tree of tm_region elements.  */
1772
1773 static struct tm_region *
1774 tm_region_init_0 (struct tm_region *outer, basic_block bb, gimple stmt)
1775 {
1776   struct tm_region *region;
1777
1778   region = (struct tm_region *)
1779     obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1780
1781   if (outer)
1782     {
1783       region->next = outer->inner;
1784       outer->inner = region;
1785     }
1786   else
1787     {
1788       region->next = all_tm_regions;
1789       all_tm_regions = region;
1790     }
1791   region->inner = NULL;
1792   region->outer = outer;
1793
1794   region->transaction_stmt = stmt;
1795
1796   /* There are either one or two edges out of the block containing
1797      the GIMPLE_TRANSACTION, one to the actual region and one to the
1798      "over" label if the region contains an abort.  The former will
1799      always be the one marked FALLTHRU.  */
1800   region->entry_block = FALLTHRU_EDGE (bb)->dest;
1801
1802   region->exit_blocks = BITMAP_ALLOC (&tm_obstack);
1803   region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1804
1805   return region;
1806 }
1807
1808 /* A subroutine of tm_region_init.  Record all the exit and
1809    irrevocable blocks in BB into the region's exit_blocks and
1810    irr_blocks bitmaps.  Returns the new region being scanned.  */
1811
1812 static struct tm_region *
1813 tm_region_init_1 (struct tm_region *region, basic_block bb)
1814 {
1815   gimple_stmt_iterator gsi;
1816   gimple g;
1817
1818   if (!region
1819       || (!region->irr_blocks && !region->exit_blocks))
1820     return region;
1821
1822   /* Check to see if this is the end of a region by seeing if it
1823      contains a call to __builtin_tm_commit{,_eh}.  Note that the
1824      outermost region for DECL_IS_TM_CLONE need not collect this.  */
1825   for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1826     {
1827       g = gsi_stmt (gsi);
1828       if (gimple_code (g) == GIMPLE_CALL)
1829         {
1830           tree fn = gimple_call_fndecl (g);
1831           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
1832             {
1833               if ((DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT
1834                    || DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_COMMIT_EH)
1835                   && region->exit_blocks)
1836                 {
1837                   bitmap_set_bit (region->exit_blocks, bb->index);
1838                   region = region->outer;
1839                   break;
1840                 }
1841               if (DECL_FUNCTION_CODE (fn) == BUILT_IN_TM_IRREVOCABLE)
1842                 bitmap_set_bit (region->irr_blocks, bb->index);
1843             }
1844         }
1845     }
1846   return region;
1847 }
1848
1849 /* Collect all of the transaction regions within the current function
1850    and record them in ALL_TM_REGIONS.  The REGION parameter may specify
1851    an "outermost" region for use by tm clones.  */
1852
1853 static void
1854 tm_region_init (struct tm_region *region)
1855 {
1856   gimple g;
1857   edge_iterator ei;
1858   edge e;
1859   basic_block bb;
1860   VEC(basic_block, heap) *queue = NULL;
1861   bitmap visited_blocks = BITMAP_ALLOC (NULL);
1862   struct tm_region *old_region;
1863
1864   all_tm_regions = region;
1865   bb = single_succ (ENTRY_BLOCK_PTR);
1866
1867   VEC_safe_push (basic_block, heap, queue, bb);
1868   gcc_assert (!bb->aux);        /* FIXME: Remove me.  */
1869   bb->aux = region;
1870   do
1871     {
1872       bb = VEC_pop (basic_block, queue);
1873       region = (struct tm_region *)bb->aux;
1874       bb->aux = NULL;
1875
1876       /* Record exit and irrevocable blocks.  */
1877       region = tm_region_init_1 (region, bb);
1878
1879       /* Check for the last statement in the block beginning a new region.  */
1880       g = last_stmt (bb);
1881       old_region = region;
1882       if (g && gimple_code (g) == GIMPLE_TRANSACTION)
1883         region = tm_region_init_0 (region, bb, g);
1884
1885       /* Process subsequent blocks.  */
1886       FOR_EACH_EDGE (e, ei, bb->succs)
1887         if (!bitmap_bit_p (visited_blocks, e->dest->index))
1888           {
1889             bitmap_set_bit (visited_blocks, e->dest->index);
1890             VEC_safe_push (basic_block, heap, queue, e->dest);
1891             gcc_assert (!e->dest->aux); /* FIXME: Remove me.  */
1892
1893             /* If the current block started a new region, make sure that only
1894                the entry block of the new region is associated with this region.
1895                Other successors are still part of the old region.  */
1896             if (old_region != region && e->dest != region->entry_block)
1897               e->dest->aux = old_region;
1898             else
1899               e->dest->aux = region;
1900           }
1901     }
1902   while (!VEC_empty (basic_block, queue));
1903   VEC_free (basic_block, heap, queue);
1904   BITMAP_FREE (visited_blocks);
1905 }
1906
1907 /* The "gate" function for all transactional memory expansion and optimization
1908    passes.  We collect region information for each top-level transaction, and
1909    if we don't find any, we skip all of the TM passes.  Each region will have
1910    all of the exit blocks recorded, and the originating statement.  */
1911
1912 static bool
1913 gate_tm_init (void)
1914 {
1915   if (!flag_tm)
1916     return false;
1917
1918   calculate_dominance_info (CDI_DOMINATORS);
1919   bitmap_obstack_initialize (&tm_obstack);
1920
1921   /* If the function is a TM_CLONE, then the entire function is the region.  */
1922   if (decl_is_tm_clone (current_function_decl))
1923     {
1924       struct tm_region *region = (struct tm_region *)
1925         obstack_alloc (&tm_obstack.obstack, sizeof (struct tm_region));
1926       memset (region, 0, sizeof (*region));
1927       region->entry_block = single_succ (ENTRY_BLOCK_PTR);
1928       /* For a clone, the entire function is the region.  But even if
1929          we don't need to record any exit blocks, we may need to
1930          record irrevocable blocks.  */
1931       region->irr_blocks = BITMAP_ALLOC (&tm_obstack);
1932
1933       tm_region_init (region);
1934     }
1935   else
1936     {
1937       tm_region_init (NULL);
1938
1939       /* If we didn't find any regions, cleanup and skip the whole tree
1940          of tm-related optimizations.  */
1941       if (all_tm_regions == NULL)
1942         {
1943           bitmap_obstack_release (&tm_obstack);
1944           return false;
1945         }
1946     }
1947
1948   return true;
1949 }
1950
1951 struct gimple_opt_pass pass_tm_init =
1952 {
1953  {
1954   GIMPLE_PASS,
1955   "*tminit",                            /* name */
1956   gate_tm_init,                         /* gate */
1957   NULL,                                 /* execute */
1958   NULL,                                 /* sub */
1959   NULL,                                 /* next */
1960   0,                                    /* static_pass_number */
1961   TV_TRANS_MEM,                         /* tv_id */
1962   PROP_ssa | PROP_cfg,                  /* properties_required */
1963   0,                                    /* properties_provided */
1964   0,                                    /* properties_destroyed */
1965   0,                                    /* todo_flags_start */
1966   0,                                    /* todo_flags_finish */
1967  }
1968 };
1969 \f
1970 /* Add FLAGS to the GIMPLE_TRANSACTION subcode for the transaction region
1971    represented by STATE.  */
1972
1973 static inline void
1974 transaction_subcode_ior (struct tm_region *region, unsigned flags)
1975 {
1976   if (region && region->transaction_stmt)
1977     {
1978       flags |= gimple_transaction_subcode (region->transaction_stmt);
1979       gimple_transaction_set_subcode (region->transaction_stmt, flags);
1980     }
1981 }
1982
1983 /* Construct a memory load in a transactional context.  Return the
1984    gimple statement performing the load, or NULL if there is no
1985    TM_LOAD builtin of the appropriate size to do the load.
1986
1987    LOC is the location to use for the new statement(s).  */
1988
1989 static gimple
1990 build_tm_load (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
1991 {
1992   enum built_in_function code = END_BUILTINS;
1993   tree t, type = TREE_TYPE (rhs), decl;
1994   gimple gcall;
1995
1996   if (type == float_type_node)
1997     code = BUILT_IN_TM_LOAD_FLOAT;
1998   else if (type == double_type_node)
1999     code = BUILT_IN_TM_LOAD_DOUBLE;
2000   else if (type == long_double_type_node)
2001     code = BUILT_IN_TM_LOAD_LDOUBLE;
2002   else if (TYPE_SIZE_UNIT (type) != NULL
2003            && host_integerp (TYPE_SIZE_UNIT (type), 1))
2004     {
2005       switch (tree_low_cst (TYPE_SIZE_UNIT (type), 1))
2006         {
2007         case 1:
2008           code = BUILT_IN_TM_LOAD_1;
2009           break;
2010         case 2:
2011           code = BUILT_IN_TM_LOAD_2;
2012           break;
2013         case 4:
2014           code = BUILT_IN_TM_LOAD_4;
2015           break;
2016         case 8:
2017           code = BUILT_IN_TM_LOAD_8;
2018           break;
2019         }
2020     }
2021
2022   if (code == END_BUILTINS)
2023     {
2024       decl = targetm.vectorize.builtin_tm_load (type);
2025       if (!decl)
2026         return NULL;
2027     }
2028   else
2029     decl = builtin_decl_explicit (code);
2030
2031   t = gimplify_addr (gsi, rhs);
2032   gcall = gimple_build_call (decl, 1, t);
2033   gimple_set_location (gcall, loc);
2034
2035   t = TREE_TYPE (TREE_TYPE (decl));
2036   if (useless_type_conversion_p (type, t))
2037     {
2038       gimple_call_set_lhs (gcall, lhs);
2039       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2040     }
2041   else
2042     {
2043       gimple g;
2044       tree temp;
2045
2046       temp = make_rename_temp (t, NULL);
2047       gimple_call_set_lhs (gcall, temp);
2048       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2049
2050       t = fold_build1 (VIEW_CONVERT_EXPR, type, temp);
2051       g = gimple_build_assign (lhs, t);
2052       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2053     }
2054
2055   return gcall;
2056 }
2057
2058
2059 /* Similarly for storing TYPE in a transactional context.  */
2060
2061 static gimple
2062 build_tm_store (location_t loc, tree lhs, tree rhs, gimple_stmt_iterator *gsi)
2063 {
2064   enum built_in_function code = END_BUILTINS;
2065   tree t, fn, type = TREE_TYPE (rhs), simple_type;
2066   gimple gcall;
2067
2068   if (type == float_type_node)
2069     code = BUILT_IN_TM_STORE_FLOAT;
2070   else if (type == double_type_node)
2071     code = BUILT_IN_TM_STORE_DOUBLE;
2072   else if (type == long_double_type_node)
2073     code = BUILT_IN_TM_STORE_LDOUBLE;
2074   else if (TYPE_SIZE_UNIT (type) != NULL
2075            && host_integerp (TYPE_SIZE_UNIT (type), 1))
2076     {
2077       switch (tree_low_cst (TYPE_SIZE_UNIT (type), 1))
2078         {
2079         case 1:
2080           code = BUILT_IN_TM_STORE_1;
2081           break;
2082         case 2:
2083           code = BUILT_IN_TM_STORE_2;
2084           break;
2085         case 4:
2086           code = BUILT_IN_TM_STORE_4;
2087           break;
2088         case 8:
2089           code = BUILT_IN_TM_STORE_8;
2090           break;
2091         }
2092     }
2093
2094   if (code == END_BUILTINS)
2095     {
2096       fn = targetm.vectorize.builtin_tm_store (type);
2097       if (!fn)
2098         return NULL;
2099     }
2100   else
2101     fn = builtin_decl_explicit (code);
2102
2103   simple_type = TREE_VALUE (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn))));
2104
2105   if (TREE_CODE (rhs) == CONSTRUCTOR)
2106     {
2107       /* Handle the easy initialization to zero.  */
2108       if (CONSTRUCTOR_ELTS (rhs) == 0)
2109         rhs = build_int_cst (simple_type, 0);
2110       else
2111         {
2112           /* ...otherwise punt to the caller and probably use
2113             BUILT_IN_TM_MEMMOVE, because we can't wrap a
2114             VIEW_CONVERT_EXPR around a CONSTRUCTOR (below) and produce
2115             valid gimple.  */
2116           return NULL;
2117         }
2118     }
2119   else if (!useless_type_conversion_p (simple_type, type))
2120     {
2121       gimple g;
2122       tree temp;
2123
2124       temp = make_rename_temp (simple_type, NULL);
2125       t = fold_build1 (VIEW_CONVERT_EXPR, simple_type, rhs);
2126       g = gimple_build_assign (temp, t);
2127       gimple_set_location (g, loc);
2128       gsi_insert_before (gsi, g, GSI_SAME_STMT);
2129
2130       rhs = temp;
2131     }
2132
2133   t = gimplify_addr (gsi, lhs);
2134   gcall = gimple_build_call (fn, 2, t, rhs);
2135   gimple_set_location (gcall, loc);
2136   gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2137
2138   return gcall;
2139 }
2140
2141
2142 /* Expand an assignment statement into transactional builtins.  */
2143
2144 static void
2145 expand_assign_tm (struct tm_region *region, gimple_stmt_iterator *gsi)
2146 {
2147   gimple stmt = gsi_stmt (*gsi);
2148   location_t loc = gimple_location (stmt);
2149   tree lhs = gimple_assign_lhs (stmt);
2150   tree rhs = gimple_assign_rhs1 (stmt);
2151   bool store_p = requires_barrier (region->entry_block, lhs, NULL);
2152   bool load_p = requires_barrier (region->entry_block, rhs, NULL);
2153   gimple gcall = NULL;
2154
2155   if (!load_p && !store_p)
2156     {
2157       /* Add thread private addresses to log if applicable.  */
2158       requires_barrier (region->entry_block, lhs, stmt);
2159       gsi_next (gsi);
2160       return;
2161     }
2162
2163   gsi_remove (gsi, true);
2164
2165   if (load_p && !store_p)
2166     {
2167       transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2168       gcall = build_tm_load (loc, lhs, rhs, gsi);
2169     }
2170   else if (store_p && !load_p)
2171     {
2172       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2173       gcall = build_tm_store (loc, lhs, rhs, gsi);
2174     }
2175   if (!gcall)
2176     {
2177       tree lhs_addr, rhs_addr;
2178
2179       if (load_p)
2180         transaction_subcode_ior (region, GTMA_HAVE_LOAD);
2181       if (store_p)
2182         transaction_subcode_ior (region, GTMA_HAVE_STORE);
2183
2184       /* ??? Figure out if there's any possible overlap between the LHS
2185          and the RHS and if not, use MEMCPY.  */
2186       lhs_addr = gimplify_addr (gsi, lhs);
2187       rhs_addr = gimplify_addr (gsi, rhs);
2188       gcall = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_MEMMOVE),
2189                                  3, lhs_addr, rhs_addr,
2190                                  TYPE_SIZE_UNIT (TREE_TYPE (lhs)));
2191       gimple_set_location (gcall, loc);
2192       gsi_insert_before (gsi, gcall, GSI_SAME_STMT);
2193     }
2194
2195   /* Now that we have the load/store in its instrumented form, add
2196      thread private addresses to the log if applicable.  */
2197   if (!store_p)
2198     requires_barrier (region->entry_block, lhs, gcall);
2199
2200   /* add_stmt_to_tm_region  (region, gcall); */
2201 }
2202
2203
2204 /* Expand a call statement as appropriate for a transaction.  That is,
2205    either verify that the call does not affect the transaction, or
2206    redirect the call to a clone that handles transactions, or change
2207    the transaction state to IRREVOCABLE.  Return true if the call is
2208    one of the builtins that end a transaction.  */
2209
2210 static bool
2211 expand_call_tm (struct tm_region *region,
2212                 gimple_stmt_iterator *gsi)
2213 {
2214   gimple stmt = gsi_stmt (*gsi);
2215   tree lhs = gimple_call_lhs (stmt);
2216   tree fn_decl;
2217   struct cgraph_node *node;
2218   bool retval = false;
2219
2220   fn_decl = gimple_call_fndecl (stmt);
2221
2222   if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMCPY)
2223       || fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMMOVE))
2224     transaction_subcode_ior (region, GTMA_HAVE_STORE | GTMA_HAVE_LOAD);
2225   if (fn_decl == builtin_decl_explicit (BUILT_IN_TM_MEMSET))
2226     transaction_subcode_ior (region, GTMA_HAVE_STORE);
2227
2228   if (is_tm_pure_call (stmt))
2229     return false;
2230
2231   if (fn_decl)
2232     retval = is_tm_ending_fndecl (fn_decl);
2233   if (!retval)
2234     {
2235       /* Assume all non-const/pure calls write to memory, except
2236          transaction ending builtins.  */
2237       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2238     }
2239
2240   /* For indirect calls, we already generated a call into the runtime.  */
2241   if (!fn_decl)
2242     {
2243       tree fn = gimple_call_fn (stmt);
2244
2245       /* We are guaranteed never to go irrevocable on a safe or pure
2246          call, and the pure call was handled above.  */
2247       if (is_tm_safe (fn))
2248         return false;
2249       else
2250         transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2251
2252       return false;
2253     }
2254
2255   node = cgraph_get_node (fn_decl);
2256   if (node->local.tm_may_enter_irr)
2257     transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
2258
2259   if (is_tm_abort (fn_decl))
2260     {
2261       transaction_subcode_ior (region, GTMA_HAVE_ABORT);
2262       return true;
2263     }
2264
2265   /* Instrument the store if needed.
2266
2267      If the assignment happens inside the function call (return slot
2268      optimization), there is no instrumentation to be done, since
2269      the callee should have done the right thing.  */
2270   if (lhs && requires_barrier (region->entry_block, lhs, stmt)
2271       && !gimple_call_return_slot_opt_p (stmt))
2272     {
2273       tree tmp = make_rename_temp (TREE_TYPE (lhs), NULL);
2274       location_t loc = gimple_location (stmt);
2275       edge fallthru_edge = NULL;
2276
2277       /* Remember if the call was going to throw.  */
2278       if (stmt_can_throw_internal (stmt))
2279         {
2280           edge_iterator ei;
2281           edge e;
2282           basic_block bb = gimple_bb (stmt);
2283
2284           FOR_EACH_EDGE (e, ei, bb->succs)
2285             if (e->flags & EDGE_FALLTHRU)
2286               {
2287                 fallthru_edge = e;
2288                 break;
2289               }
2290         }
2291
2292       gimple_call_set_lhs (stmt, tmp);
2293       update_stmt (stmt);
2294       stmt = gimple_build_assign (lhs, tmp);
2295       gimple_set_location (stmt, loc);
2296
2297       /* We cannot throw in the middle of a BB.  If the call was going
2298          to throw, place the instrumentation on the fallthru edge, so
2299          the call remains the last statement in the block.  */
2300       if (fallthru_edge)
2301         {
2302           gimple_seq fallthru_seq = gimple_seq_alloc_with_stmt (stmt);
2303           gimple_stmt_iterator fallthru_gsi = gsi_start (fallthru_seq);
2304           expand_assign_tm (region, &fallthru_gsi);
2305           gsi_insert_seq_on_edge (fallthru_edge, fallthru_seq);
2306           pending_edge_inserts_p = true;
2307         }
2308       else
2309         {
2310           gsi_insert_after (gsi, stmt, GSI_CONTINUE_LINKING);
2311           expand_assign_tm (region, gsi);
2312         }
2313
2314       transaction_subcode_ior (region, GTMA_HAVE_STORE);
2315     }
2316
2317   return retval;
2318 }
2319
2320
2321 /* Expand all statements in BB as appropriate for being inside
2322    a transaction.  */
2323
2324 static void
2325 expand_block_tm (struct tm_region *region, basic_block bb)
2326 {
2327   gimple_stmt_iterator gsi;
2328
2329   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2330     {
2331       gimple stmt = gsi_stmt (gsi);
2332       switch (gimple_code (stmt))
2333         {
2334         case GIMPLE_ASSIGN:
2335           /* Only memory reads/writes need to be instrumented.  */
2336           if (gimple_assign_single_p (stmt))
2337             {
2338               expand_assign_tm (region, &gsi);
2339               continue;
2340             }
2341           break;
2342
2343         case GIMPLE_CALL:
2344           if (expand_call_tm (region, &gsi))
2345             return;
2346           break;
2347
2348         case GIMPLE_ASM:
2349           gcc_unreachable ();
2350
2351         default:
2352           break;
2353         }
2354       if (!gsi_end_p (gsi))
2355         gsi_next (&gsi);
2356     }
2357 }
2358
2359 /* Return the list of basic-blocks in REGION.
2360
2361    STOP_AT_IRREVOCABLE_P is true if caller is uninterested in blocks
2362    following a TM_IRREVOCABLE call.  */
2363
2364 static VEC (basic_block, heap) *
2365 get_tm_region_blocks (basic_block entry_block,
2366                       bitmap exit_blocks,
2367                       bitmap irr_blocks,
2368                       bitmap all_region_blocks,
2369                       bool stop_at_irrevocable_p)
2370 {
2371   VEC(basic_block, heap) *bbs = NULL;
2372   unsigned i;
2373   edge e;
2374   edge_iterator ei;
2375   bitmap visited_blocks = BITMAP_ALLOC (NULL);
2376
2377   i = 0;
2378   VEC_safe_push (basic_block, heap, bbs, entry_block);
2379   bitmap_set_bit (visited_blocks, entry_block->index);
2380
2381   do
2382     {
2383       basic_block bb = VEC_index (basic_block, bbs, i++);
2384
2385       if (exit_blocks &&
2386           bitmap_bit_p (exit_blocks, bb->index))
2387         continue;
2388
2389       if (stop_at_irrevocable_p
2390           && irr_blocks
2391           && bitmap_bit_p (irr_blocks, bb->index))
2392         continue;
2393
2394       FOR_EACH_EDGE (e, ei, bb->succs)
2395         if (!bitmap_bit_p (visited_blocks, e->dest->index))
2396           {
2397             bitmap_set_bit (visited_blocks, e->dest->index);
2398             VEC_safe_push (basic_block, heap, bbs, e->dest);
2399           }
2400     }
2401   while (i < VEC_length (basic_block, bbs));
2402
2403   if (all_region_blocks)
2404     bitmap_ior_into (all_region_blocks, visited_blocks);
2405
2406   BITMAP_FREE (visited_blocks);
2407   return bbs;
2408 }
2409
2410 /* Entry point to the MARK phase of TM expansion.  Here we replace
2411    transactional memory statements with calls to builtins, and function
2412    calls with their transactional clones (if available).  But we don't
2413    yet lower GIMPLE_TRANSACTION or add the transaction restart back-edges.  */
2414
2415 static unsigned int
2416 execute_tm_mark (void)
2417 {
2418   struct tm_region *region;
2419   basic_block bb;
2420   VEC (basic_block, heap) *queue;
2421   size_t i;
2422
2423   queue = VEC_alloc (basic_block, heap, 10);
2424   pending_edge_inserts_p = false;
2425
2426   for (region = all_tm_regions; region ; region = region->next)
2427     {
2428       tm_log_init ();
2429       /* If we have a transaction...  */
2430       if (region->exit_blocks)
2431         {
2432           unsigned int subcode
2433             = gimple_transaction_subcode (region->transaction_stmt);
2434
2435           /* Collect a new SUBCODE set, now that optimizations are done...  */
2436           if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2437             subcode &= (GTMA_DECLARATION_MASK | GTMA_DOES_GO_IRREVOCABLE
2438                         | GTMA_MAY_ENTER_IRREVOCABLE);
2439           else
2440             subcode &= GTMA_DECLARATION_MASK;
2441           gimple_transaction_set_subcode (region->transaction_stmt, subcode);
2442         }
2443
2444       queue = get_tm_region_blocks (region->entry_block,
2445                                     region->exit_blocks,
2446                                     region->irr_blocks,
2447                                     NULL,
2448                                     /*stop_at_irr_p=*/true);
2449       for (i = 0; VEC_iterate (basic_block, queue, i, bb); ++i)
2450         expand_block_tm (region, bb);
2451       VEC_free (basic_block, heap, queue);
2452
2453       tm_log_emit ();
2454     }
2455
2456   if (pending_edge_inserts_p)
2457     gsi_commit_edge_inserts ();
2458   return 0;
2459 }
2460
2461 struct gimple_opt_pass pass_tm_mark =
2462 {
2463  {
2464   GIMPLE_PASS,
2465   "tmmark",                             /* name */
2466   NULL,                                 /* gate */
2467   execute_tm_mark,                      /* execute */
2468   NULL,                                 /* sub */
2469   NULL,                                 /* next */
2470   0,                                    /* static_pass_number */
2471   TV_TRANS_MEM,                         /* tv_id */
2472   PROP_ssa | PROP_cfg,                  /* properties_required */
2473   0,                                    /* properties_provided */
2474   0,                                    /* properties_destroyed */
2475   0,                                    /* todo_flags_start */
2476   TODO_update_ssa
2477   | TODO_verify_ssa
2478   | TODO_dump_func,                     /* todo_flags_finish */
2479  }
2480 };
2481 \f
2482 /* Create an abnormal call edge from BB to the first block of the region
2483    represented by STATE.  Also record the edge in the TM_RESTART map.  */
2484
2485 static inline void
2486 make_tm_edge (gimple stmt, basic_block bb, struct tm_region *region)
2487 {
2488   void **slot;
2489   struct tm_restart_node *n, dummy;
2490
2491   if (cfun->gimple_df->tm_restart == NULL)
2492     cfun->gimple_df->tm_restart = htab_create_ggc (31, struct_ptr_hash,
2493                                                    struct_ptr_eq, ggc_free);
2494
2495   dummy.stmt = stmt;
2496   dummy.label_or_list = gimple_block_label (region->entry_block);
2497   slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, INSERT);
2498   n = (struct tm_restart_node *) *slot;
2499   if (n == NULL)
2500     {
2501       n = ggc_alloc_tm_restart_node ();
2502       *n = dummy;
2503     }
2504   else
2505     {
2506       tree old = n->label_or_list;
2507       if (TREE_CODE (old) == LABEL_DECL)
2508         old = tree_cons (NULL, old, NULL);
2509       n->label_or_list = tree_cons (NULL, dummy.label_or_list, old);
2510     }
2511
2512   make_edge (bb, region->entry_block, EDGE_ABNORMAL | EDGE_ABNORMAL_CALL);
2513 }
2514
2515
2516 /* Split block BB as necessary for every builtin function we added, and
2517    wire up the abnormal back edges implied by the transaction restart.  */
2518
2519 static void
2520 expand_block_edges (struct tm_region *region, basic_block bb)
2521 {
2522   gimple_stmt_iterator gsi;
2523
2524   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2525     {
2526       gimple stmt = gsi_stmt (gsi);
2527
2528       /* ??? TM_COMMIT (and any other tm builtin function) in a nested
2529          transaction has an abnormal edge back to the outer-most transaction
2530          (there are no nested retries), while a TM_ABORT also has an abnormal
2531          backedge to the inner-most transaction.  We haven't actually saved
2532          the inner-most transaction here.  We should be able to get to it
2533          via the region_nr saved on STMT, and read the transaction_stmt from
2534          that, and find the first region block from there.  */
2535       /* ??? Shouldn't we split for any non-pure, non-irrevocable function?  */
2536       if (gimple_code (stmt) == GIMPLE_CALL
2537           && (gimple_call_flags (stmt) & ECF_TM_BUILTIN) != 0)
2538         {
2539           if (gsi_one_before_end_p (gsi))
2540             make_tm_edge (stmt, bb, region);
2541           else
2542             {
2543               edge e = split_block (bb, stmt);
2544               make_tm_edge (stmt, bb, region);
2545               bb = e->dest;
2546               gsi = gsi_start_bb (bb);
2547             }
2548
2549           /* Delete any tail-call annotation that may have been added.
2550              The tail-call pass may have mis-identified the commit as being
2551              a candidate because we had not yet added this restart edge.  */
2552           gimple_call_set_tail (stmt, false);
2553         }
2554
2555       gsi_next (&gsi);
2556     }
2557 }
2558
2559 /* Expand the GIMPLE_TRANSACTION statement into the STM library call.  */
2560
2561 static void
2562 expand_transaction (struct tm_region *region)
2563 {
2564   tree status, tm_start;
2565   basic_block atomic_bb, slice_bb;
2566   gimple_stmt_iterator gsi;
2567   tree t1, t2;
2568   gimple g;
2569   int flags, subcode;
2570
2571   tm_start = builtin_decl_explicit (BUILT_IN_TM_START);
2572   status = make_rename_temp (TREE_TYPE (TREE_TYPE (tm_start)), "tm_state");
2573
2574   /* ??? There are plenty of bits here we're not computing.  */
2575   subcode = gimple_transaction_subcode (region->transaction_stmt);
2576   if (subcode & GTMA_DOES_GO_IRREVOCABLE)
2577     flags = PR_DOESGOIRREVOCABLE | PR_UNINSTRUMENTEDCODE;
2578   else
2579     flags = PR_INSTRUMENTEDCODE;
2580   if ((subcode & GTMA_MAY_ENTER_IRREVOCABLE) == 0)
2581     flags |= PR_HASNOIRREVOCABLE;
2582   /* If the transaction does not have an abort in lexical scope and is not
2583      marked as an outer transaction, then it will never abort.  */
2584   if ((subcode & GTMA_HAVE_ABORT) == 0
2585       && (subcode & GTMA_IS_OUTER) == 0)
2586     flags |= PR_HASNOABORT;
2587   if ((subcode & GTMA_HAVE_STORE) == 0)
2588     flags |= PR_READONLY;
2589   t2 = build_int_cst (TREE_TYPE (status), flags);
2590   g = gimple_build_call (tm_start, 1, t2);
2591   gimple_call_set_lhs (g, status);
2592   gimple_set_location (g, gimple_location (region->transaction_stmt));
2593
2594   atomic_bb = gimple_bb (region->transaction_stmt);
2595
2596   if (!VEC_empty (tree, tm_log_save_addresses))
2597     tm_log_emit_saves (region->entry_block, atomic_bb);
2598
2599   gsi = gsi_last_bb (atomic_bb);
2600   gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2601   gsi_remove (&gsi, true);
2602
2603   if (!VEC_empty (tree, tm_log_save_addresses))
2604     region->entry_block =
2605       tm_log_emit_save_or_restores (region->entry_block,
2606                                     A_RESTORELIVEVARIABLES,
2607                                     status,
2608                                     tm_log_emit_restores,
2609                                     atomic_bb,
2610                                     FALLTHRU_EDGE (atomic_bb),
2611                                     &slice_bb);
2612   else
2613     slice_bb = atomic_bb;
2614
2615   /* If we have an ABORT statement, create a test following the start
2616      call to perform the abort.  */
2617   if (gimple_transaction_label (region->transaction_stmt))
2618     {
2619       edge e;
2620       basic_block test_bb;
2621
2622       test_bb = create_empty_bb (slice_bb);
2623       if (VEC_empty (tree, tm_log_save_addresses))
2624         region->entry_block = test_bb;
2625       gsi = gsi_last_bb (test_bb);
2626
2627       t1 = make_rename_temp (TREE_TYPE (status), NULL);
2628       t2 = build_int_cst (TREE_TYPE (status), A_ABORTTRANSACTION);
2629       g = gimple_build_assign_with_ops (BIT_AND_EXPR, t1, status, t2);
2630       gsi_insert_after (&gsi, g, GSI_CONTINUE_LINKING);
2631
2632       t2 = build_int_cst (TREE_TYPE (status), 0);
2633       g = gimple_build_cond (NE_EXPR, t1, t2, NULL, NULL);
2634       gsi_insert_after (&gsi, g, GSI_CONTINUE_LINKING);
2635
2636       e = FALLTHRU_EDGE (slice_bb);
2637       redirect_edge_pred (e, test_bb);
2638       e->flags = EDGE_FALSE_VALUE;
2639       e->probability = PROB_ALWAYS - PROB_VERY_UNLIKELY;
2640
2641       e = BRANCH_EDGE (atomic_bb);
2642       redirect_edge_pred (e, test_bb);
2643       e->flags = EDGE_TRUE_VALUE;
2644       e->probability = PROB_VERY_UNLIKELY;
2645
2646       e = make_edge (slice_bb, test_bb, EDGE_FALLTHRU);
2647     }
2648
2649   /* If we've no abort, but we do have PHIs at the beginning of the atomic
2650      region, that means we've a loop at the beginning of the atomic region
2651      that shares the first block.  This can cause problems with the abnormal
2652      edges we're about to add for the transaction restart.  Solve this by
2653      adding a new empty block to receive the abnormal edges.  */
2654   else if (phi_nodes (region->entry_block))
2655     {
2656       edge e;
2657       basic_block empty_bb;
2658
2659       region->entry_block = empty_bb = create_empty_bb (atomic_bb);
2660
2661       e = FALLTHRU_EDGE (atomic_bb);
2662       redirect_edge_pred (e, empty_bb);
2663
2664       e = make_edge (atomic_bb, empty_bb, EDGE_FALLTHRU);
2665     }
2666
2667   /* The GIMPLE_TRANSACTION statement no longer exists.  */
2668   region->transaction_stmt = NULL;
2669 }
2670
2671 static void expand_regions (struct tm_region *);
2672
2673 /* Helper function for expand_regions.  Expand REGION and recurse to
2674    the inner region.  */
2675
2676 static void
2677 expand_regions_1 (struct tm_region *region)
2678 {
2679   if (region->exit_blocks)
2680     {
2681       unsigned int i;
2682       basic_block bb;
2683       VEC (basic_block, heap) *queue;
2684
2685       /* Collect the set of blocks in this region.  Do this before
2686          splitting edges, so that we don't have to play with the
2687          dominator tree in the middle.  */
2688       queue = get_tm_region_blocks (region->entry_block,
2689                                     region->exit_blocks,
2690                                     region->irr_blocks,
2691                                     NULL,
2692                                     /*stop_at_irr_p=*/false);
2693       expand_transaction (region);
2694       for (i = 0; VEC_iterate (basic_block, queue, i, bb); ++i)
2695         expand_block_edges (region, bb);
2696       VEC_free (basic_block, heap, queue);
2697     }
2698   if (region->inner)
2699     expand_regions (region->inner);
2700 }
2701
2702 /* Expand regions starting at REGION.  */
2703
2704 static void
2705 expand_regions (struct tm_region *region)
2706 {
2707   while (region)
2708     {
2709       expand_regions_1 (region);
2710       region = region->next;
2711     }
2712 }
2713
2714 /* Entry point to the final expansion of transactional nodes. */
2715
2716 static unsigned int
2717 execute_tm_edges (void)
2718 {
2719   expand_regions (all_tm_regions);
2720   tm_log_delete ();
2721
2722   /* We've got to release the dominance info now, to indicate that it
2723      must be rebuilt completely.  Otherwise we'll crash trying to update
2724      the SSA web in the TODO section following this pass.  */
2725   free_dominance_info (CDI_DOMINATORS);
2726   bitmap_obstack_release (&tm_obstack);
2727   all_tm_regions = NULL;
2728
2729   return 0;
2730 }
2731
2732 struct gimple_opt_pass pass_tm_edges =
2733 {
2734  {
2735   GIMPLE_PASS,
2736   "tmedge",                             /* name */
2737   NULL,                                 /* gate */
2738   execute_tm_edges,                     /* execute */
2739   NULL,                                 /* sub */
2740   NULL,                                 /* next */
2741   0,                                    /* static_pass_number */
2742   TV_TRANS_MEM,                         /* tv_id */
2743   PROP_ssa | PROP_cfg,                  /* properties_required */
2744   0,                                    /* properties_provided */
2745   0,                                    /* properties_destroyed */
2746   0,                                    /* todo_flags_start */
2747   TODO_update_ssa
2748   | TODO_verify_ssa
2749   | TODO_dump_func,                     /* todo_flags_finish */
2750  }
2751 };
2752 \f
2753 /* A unique TM memory operation.  */
2754 typedef struct tm_memop
2755 {
2756   /* Unique ID that all memory operations to the same location have.  */
2757   unsigned int value_id;
2758   /* Address of load/store.  */
2759   tree addr;
2760 } *tm_memop_t;
2761
2762 /* Sets for solving data flow equations in the memory optimization pass.  */
2763 struct tm_memopt_bitmaps
2764 {
2765   /* Stores available to this BB upon entry.  Basically, stores that
2766      dominate this BB.  */
2767   bitmap store_avail_in;
2768   /* Stores available at the end of this BB.  */
2769   bitmap store_avail_out;
2770   bitmap store_antic_in;
2771   bitmap store_antic_out;
2772   /* Reads available to this BB upon entry.  Basically, reads that
2773      dominate this BB.  */
2774   bitmap read_avail_in;
2775   /* Reads available at the end of this BB.  */
2776   bitmap read_avail_out;
2777   /* Reads performed in this BB.  */
2778   bitmap read_local;
2779   /* Writes performed in this BB.  */
2780   bitmap store_local;
2781
2782   /* Temporary storage for pass.  */
2783   /* Is the current BB in the worklist?  */
2784   bool avail_in_worklist_p;
2785   /* Have we visited this BB?  */
2786   bool visited_p;
2787 };
2788
2789 static bitmap_obstack tm_memopt_obstack;
2790
2791 /* Unique counter for TM loads and stores. Loads and stores of the
2792    same address get the same ID.  */
2793 static unsigned int tm_memopt_value_id;
2794 static htab_t tm_memopt_value_numbers;
2795
2796 #define STORE_AVAIL_IN(BB) \
2797   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_in
2798 #define STORE_AVAIL_OUT(BB) \
2799   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_avail_out
2800 #define STORE_ANTIC_IN(BB) \
2801   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_in
2802 #define STORE_ANTIC_OUT(BB) \
2803   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_antic_out
2804 #define READ_AVAIL_IN(BB) \
2805   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_in
2806 #define READ_AVAIL_OUT(BB) \
2807   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_avail_out
2808 #define READ_LOCAL(BB) \
2809   ((struct tm_memopt_bitmaps *) ((BB)->aux))->read_local
2810 #define STORE_LOCAL(BB) \
2811   ((struct tm_memopt_bitmaps *) ((BB)->aux))->store_local
2812 #define AVAIL_IN_WORKLIST_P(BB) \
2813   ((struct tm_memopt_bitmaps *) ((BB)->aux))->avail_in_worklist_p
2814 #define BB_VISITED_P(BB) \
2815   ((struct tm_memopt_bitmaps *) ((BB)->aux))->visited_p
2816
2817 /* Htab support.  Return a hash value for a `tm_memop'.  */
2818 static hashval_t
2819 tm_memop_hash (const void *p)
2820 {
2821   const struct tm_memop *mem = (const struct tm_memop *) p;
2822   tree addr = mem->addr;
2823   /* We drill down to the SSA_NAME/DECL for the hash, but equality is
2824      actually done with operand_equal_p (see tm_memop_eq).  */
2825   if (TREE_CODE (addr) == ADDR_EXPR)
2826     addr = TREE_OPERAND (addr, 0);
2827   return iterative_hash_expr (addr, 0);
2828 }
2829
2830 /* Htab support.  Return true if two tm_memop's are the same.  */
2831 static int
2832 tm_memop_eq (const void *p1, const void *p2)
2833 {
2834   const struct tm_memop *mem1 = (const struct tm_memop *) p1;
2835   const struct tm_memop *mem2 = (const struct tm_memop *) p2;
2836
2837   return operand_equal_p (mem1->addr, mem2->addr, 0);
2838 }
2839
2840 /* Given a TM load/store in STMT, return the value number for the address
2841    it accesses.  */
2842
2843 static unsigned int
2844 tm_memopt_value_number (gimple stmt, enum insert_option op)
2845 {
2846   struct tm_memop tmpmem, *mem;
2847   void **slot;
2848
2849   gcc_assert (is_tm_load (stmt) || is_tm_store (stmt));
2850   tmpmem.addr = gimple_call_arg (stmt, 0);
2851   slot = htab_find_slot (tm_memopt_value_numbers, &tmpmem, op);
2852   if (*slot)
2853     mem = (struct tm_memop *) *slot;
2854   else if (op == INSERT)
2855     {
2856       mem = XNEW (struct tm_memop);
2857       *slot = mem;
2858       mem->value_id = tm_memopt_value_id++;
2859       mem->addr = tmpmem.addr;
2860     }
2861   else
2862     gcc_unreachable ();
2863   return mem->value_id;
2864 }
2865
2866 /* Accumulate TM memory operations in BB into STORE_LOCAL and READ_LOCAL.  */
2867
2868 static void
2869 tm_memopt_accumulate_memops (basic_block bb)
2870 {
2871   gimple_stmt_iterator gsi;
2872
2873   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2874     {
2875       gimple stmt = gsi_stmt (gsi);
2876       bitmap bits;
2877       unsigned int loc;
2878
2879       if (is_tm_store (stmt))
2880         bits = STORE_LOCAL (bb);
2881       else if (is_tm_load (stmt))
2882         bits = READ_LOCAL (bb);
2883       else
2884         continue;
2885
2886       loc = tm_memopt_value_number (stmt, INSERT);
2887       bitmap_set_bit (bits, loc);
2888       if (dump_file)
2889         {
2890           fprintf (dump_file, "TM memopt (%s): value num=%d, BB=%d, addr=",
2891                    is_tm_load (stmt) ? "LOAD" : "STORE", loc,
2892                    gimple_bb (stmt)->index);
2893           print_generic_expr (dump_file, gimple_call_arg (stmt, 0), 0);
2894           fprintf (dump_file, "\n");
2895         }
2896     }
2897 }
2898
2899 /* Prettily dump one of the memopt sets.  BITS is the bitmap to dump.  */
2900
2901 static void
2902 dump_tm_memopt_set (const char *set_name, bitmap bits)
2903 {
2904   unsigned i;
2905   bitmap_iterator bi;
2906   const char *comma = "";
2907
2908   fprintf (dump_file, "TM memopt: %s: [", set_name);
2909   EXECUTE_IF_SET_IN_BITMAP (bits, 0, i, bi)
2910     {
2911       htab_iterator hi;
2912       struct tm_memop *mem;
2913
2914       /* Yeah, yeah, yeah.  Whatever.  This is just for debugging.  */
2915       FOR_EACH_HTAB_ELEMENT (tm_memopt_value_numbers, mem, tm_memop_t, hi)
2916         if (mem->value_id == i)
2917           break;
2918       gcc_assert (mem->value_id == i);
2919       fprintf (dump_file, "%s", comma);
2920       comma = ", ";
2921       print_generic_expr (dump_file, mem->addr, 0);
2922     }
2923   fprintf (dump_file, "]\n");
2924 }
2925
2926 /* Prettily dump all of the memopt sets in BLOCKS.  */
2927
2928 static void
2929 dump_tm_memopt_sets (VEC (basic_block, heap) *blocks)
2930 {
2931   size_t i;
2932   basic_block bb;
2933
2934   for (i = 0; VEC_iterate (basic_block, blocks, i, bb); ++i)
2935     {
2936       fprintf (dump_file, "------------BB %d---------\n", bb->index);
2937       dump_tm_memopt_set ("STORE_LOCAL", STORE_LOCAL (bb));
2938       dump_tm_memopt_set ("READ_LOCAL", READ_LOCAL (bb));
2939       dump_tm_memopt_set ("STORE_AVAIL_IN", STORE_AVAIL_IN (bb));
2940       dump_tm_memopt_set ("STORE_AVAIL_OUT", STORE_AVAIL_OUT (bb));
2941       dump_tm_memopt_set ("READ_AVAIL_IN", READ_AVAIL_IN (bb));
2942       dump_tm_memopt_set ("READ_AVAIL_OUT", READ_AVAIL_OUT (bb));
2943     }
2944 }
2945
2946 /* Compute {STORE,READ}_AVAIL_IN for the basic block BB.  */
2947
2948 static void
2949 tm_memopt_compute_avin (basic_block bb)
2950 {
2951   edge e;
2952   unsigned ix;
2953
2954   /* Seed with the AVOUT of any predecessor.  */
2955   for (ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
2956     {
2957       e = EDGE_PRED (bb, ix);
2958       /* Make sure we have already visited this BB, and is thus
2959          initialized.
2960
2961           If e->src->aux is NULL, this predecessor is actually on an
2962           enclosing transaction.  We only care about the current
2963           transaction, so ignore it.  */
2964       if (e->src->aux && BB_VISITED_P (e->src))
2965         {
2966           bitmap_copy (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
2967           bitmap_copy (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
2968           break;
2969         }
2970     }
2971
2972   for (; ix < EDGE_COUNT (bb->preds); ix++)
2973     {
2974       e = EDGE_PRED (bb, ix);
2975       if (e->src->aux && BB_VISITED_P (e->src))
2976         {
2977           bitmap_and_into (STORE_AVAIL_IN (bb), STORE_AVAIL_OUT (e->src));
2978           bitmap_and_into (READ_AVAIL_IN (bb), READ_AVAIL_OUT (e->src));
2979         }
2980     }
2981
2982   BB_VISITED_P (bb) = true;
2983 }
2984
2985 /* Compute the STORE_ANTIC_IN for the basic block BB.  */
2986
2987 static void
2988 tm_memopt_compute_antin (basic_block bb)
2989 {
2990   edge e;
2991   unsigned ix;
2992
2993   /* Seed with the ANTIC_OUT of any successor.  */
2994   for (ix = 0; ix < EDGE_COUNT (bb->succs); ix++)
2995     {
2996       e = EDGE_SUCC (bb, ix);
2997       /* Make sure we have already visited this BB, and is thus
2998          initialized.  */
2999       if (BB_VISITED_P (e->dest))
3000         {
3001           bitmap_copy (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3002           break;
3003         }
3004     }
3005
3006   for (; ix < EDGE_COUNT (bb->succs); ix++)
3007     {
3008       e = EDGE_SUCC (bb, ix);
3009       if (BB_VISITED_P  (e->dest))
3010         bitmap_and_into (STORE_ANTIC_IN (bb), STORE_ANTIC_OUT (e->dest));
3011     }
3012
3013   BB_VISITED_P (bb) = true;
3014 }
3015
3016 /* Compute the AVAIL sets for every basic block in BLOCKS.
3017
3018    We compute {STORE,READ}_AVAIL_{OUT,IN} as follows:
3019
3020      AVAIL_OUT[bb] = union (AVAIL_IN[bb], LOCAL[bb])
3021      AVAIL_IN[bb]  = intersect (AVAIL_OUT[predecessors])
3022
3023    This is basically what we do in lcm's compute_available(), but here
3024    we calculate two sets of sets (one for STOREs and one for READs),
3025    and we work on a region instead of the entire CFG.
3026
3027    REGION is the TM region.
3028    BLOCKS are the basic blocks in the region.  */
3029
3030 static void
3031 tm_memopt_compute_available (struct tm_region *region,
3032                              VEC (basic_block, heap) *blocks)
3033 {
3034   edge e;
3035   basic_block *worklist, *qin, *qout, *qend, bb;
3036   unsigned int qlen, i;
3037   edge_iterator ei;
3038   bool changed;
3039
3040   /* Allocate a worklist array/queue.  Entries are only added to the
3041      list if they were not already on the list.  So the size is
3042      bounded by the number of basic blocks in the region.  */
3043   qlen = VEC_length (basic_block, blocks) - 1;
3044   qin = qout = worklist =
3045     XNEWVEC (basic_block, qlen);
3046
3047   /* Put every block in the region on the worklist.  */
3048   for (i = 0; VEC_iterate (basic_block, blocks, i, bb); ++i)
3049     {
3050       /* Seed AVAIL_OUT with the LOCAL set.  */
3051       bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_LOCAL (bb));
3052       bitmap_ior_into (READ_AVAIL_OUT (bb), READ_LOCAL (bb));
3053
3054       AVAIL_IN_WORKLIST_P (bb) = true;
3055       /* No need to insert the entry block, since it has an AVIN of
3056          null, and an AVOUT that has already been seeded in.  */
3057       if (bb != region->entry_block)
3058         *qin++ = bb;
3059     }
3060
3061   /* The entry block has been initialized with the local sets.  */
3062   BB_VISITED_P (region->entry_block) = true;
3063
3064   qin = worklist;
3065   qend = &worklist[qlen];
3066
3067   /* Iterate until the worklist is empty.  */
3068   while (qlen)
3069     {
3070       /* Take the first entry off the worklist.  */
3071       bb = *qout++;
3072       qlen--;
3073
3074       if (qout >= qend)
3075         qout = worklist;
3076
3077       /* This block can be added to the worklist again if necessary.  */
3078       AVAIL_IN_WORKLIST_P (bb) = false;
3079       tm_memopt_compute_avin (bb);
3080
3081       /* Note: We do not add the LOCAL sets here because we already
3082          seeded the AVAIL_OUT sets with them.  */
3083       changed  = bitmap_ior_into (STORE_AVAIL_OUT (bb), STORE_AVAIL_IN (bb));
3084       changed |= bitmap_ior_into (READ_AVAIL_OUT (bb), READ_AVAIL_IN (bb));
3085       if (changed
3086           && (region->exit_blocks == NULL
3087               || !bitmap_bit_p (region->exit_blocks, bb->index)))
3088         /* If the out state of this block changed, then we need to add
3089            its successors to the worklist if they are not already in.  */
3090         FOR_EACH_EDGE (e, ei, bb->succs)
3091           if (!AVAIL_IN_WORKLIST_P (e->dest) && e->dest != EXIT_BLOCK_PTR)
3092             {
3093               *qin++ = e->dest;
3094               AVAIL_IN_WORKLIST_P (e->dest) = true;
3095               qlen++;
3096
3097               if (qin >= qend)
3098                 qin = worklist;
3099             }
3100     }
3101
3102   free (worklist);
3103
3104   if (dump_file)
3105     dump_tm_memopt_sets (blocks);
3106 }
3107
3108 /* Compute ANTIC sets for every basic block in BLOCKS.
3109
3110    We compute STORE_ANTIC_OUT as follows:
3111
3112         STORE_ANTIC_OUT[bb] = union(STORE_ANTIC_IN[bb], STORE_LOCAL[bb])
3113         STORE_ANTIC_IN[bb]  = intersect(STORE_ANTIC_OUT[successors])
3114
3115    REGION is the TM region.
3116    BLOCKS are the basic blocks in the region.  */
3117
3118 static void
3119 tm_memopt_compute_antic (struct tm_region *region,
3120                          VEC (basic_block, heap) *blocks)
3121 {
3122   edge e;
3123   basic_block *worklist, *qin, *qout, *qend, bb;
3124   unsigned int qlen;
3125   int i;
3126   edge_iterator ei;
3127
3128   /* Allocate a worklist array/queue.  Entries are only added to the
3129      list if they were not already on the list.  So the size is
3130      bounded by the number of basic blocks in the region.  */
3131   qin = qout = worklist =
3132     XNEWVEC (basic_block, VEC_length (basic_block, blocks));
3133
3134   for (qlen = 0, i = VEC_length (basic_block, blocks) - 1; i >= 0; --i)
3135     {
3136       bb = VEC_index (basic_block, blocks, i);
3137
3138       /* Seed ANTIC_OUT with the LOCAL set.  */
3139       bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_LOCAL (bb));
3140
3141       /* Put every block in the region on the worklist.  */
3142       AVAIL_IN_WORKLIST_P (bb) = true;
3143       /* No need to insert exit blocks, since their ANTIC_IN is NULL,
3144          and their ANTIC_OUT has already been seeded in.  */
3145       if (region->exit_blocks
3146           && !bitmap_bit_p (region->exit_blocks, bb->index))
3147         {
3148           qlen++;
3149           *qin++ = bb;
3150         }
3151     }
3152
3153   /* The exit blocks have been initialized with the local sets.  */
3154   if (region->exit_blocks)
3155     {
3156       unsigned int i;
3157       bitmap_iterator bi;
3158       EXECUTE_IF_SET_IN_BITMAP (region->exit_blocks, 0, i, bi)
3159         BB_VISITED_P (BASIC_BLOCK (i)) = true;
3160     }
3161
3162   qin = worklist;
3163   qend = &worklist[qlen];
3164
3165   /* Iterate until the worklist is empty.  */
3166   while (qlen)
3167     {
3168       /* Take the first entry off the worklist.  */
3169       bb = *qout++;
3170       qlen--;
3171
3172       if (qout >= qend)
3173         qout = worklist;
3174
3175       /* This block can be added to the worklist again if necessary.  */
3176       AVAIL_IN_WORKLIST_P (bb) = false;
3177       tm_memopt_compute_antin (bb);
3178
3179       /* Note: We do not add the LOCAL sets here because we already
3180          seeded the ANTIC_OUT sets with them.  */
3181       if (bitmap_ior_into (STORE_ANTIC_OUT (bb), STORE_ANTIC_IN (bb))
3182           && bb != region->entry_block)
3183         /* If the out state of this block changed, then we need to add
3184            its predecessors to the worklist if they are not already in.  */
3185         FOR_EACH_EDGE (e, ei, bb->preds)
3186           if (!AVAIL_IN_WORKLIST_P (e->src))
3187             {
3188               *qin++ = e->src;
3189               AVAIL_IN_WORKLIST_P (e->src) = true;
3190               qlen++;
3191
3192               if (qin >= qend)
3193                 qin = worklist;
3194             }
3195     }
3196
3197   free (worklist);
3198
3199   if (dump_file)
3200     dump_tm_memopt_sets (blocks);
3201 }
3202
3203 /* Offsets of load variants from TM_LOAD.  For example,
3204    BUILT_IN_TM_LOAD_RAR* is an offset of 1 from BUILT_IN_TM_LOAD*.
3205    See gtm-builtins.def.  */
3206 #define TRANSFORM_RAR 1
3207 #define TRANSFORM_RAW 2
3208 #define TRANSFORM_RFW 3
3209 /* Offsets of store variants from TM_STORE.  */
3210 #define TRANSFORM_WAR 1
3211 #define TRANSFORM_WAW 2
3212
3213 /* Inform about a load/store optimization.  */
3214
3215 static void
3216 dump_tm_memopt_transform (gimple stmt)
3217 {
3218   if (dump_file)
3219     {
3220       fprintf (dump_file, "TM memopt: transforming: ");
3221       print_gimple_stmt (dump_file, stmt, 0, 0);
3222       fprintf (dump_file, "\n");
3223     }
3224 }
3225
3226 /* Perform a read/write optimization.  Replaces the TM builtin in STMT
3227    by a builtin that is OFFSET entries down in the builtins table in
3228    gtm-builtins.def.  */
3229
3230 static void
3231 tm_memopt_transform_stmt (unsigned int offset,
3232                           gimple stmt,
3233                           gimple_stmt_iterator *gsi)
3234 {
3235   tree fn = gimple_call_fn (stmt);
3236   gcc_assert (TREE_CODE (fn) == ADDR_EXPR);
3237   TREE_OPERAND (fn, 0)
3238     = builtin_decl_explicit ((enum built_in_function)
3239                              (DECL_FUNCTION_CODE (TREE_OPERAND (fn, 0))
3240                               + offset));
3241   gimple_call_set_fn (stmt, fn);
3242   gsi_replace (gsi, stmt, true);
3243   dump_tm_memopt_transform (stmt);
3244 }
3245
3246 /* Perform the actual TM memory optimization transformations in the
3247    basic blocks in BLOCKS.  */
3248
3249 static void
3250 tm_memopt_transform_blocks (VEC (basic_block, heap) *blocks)
3251 {
3252   size_t i;
3253   basic_block bb;
3254   gimple_stmt_iterator gsi;
3255
3256   for (i = 0; VEC_iterate (basic_block, blocks, i, bb); ++i)
3257     {
3258       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3259         {
3260           gimple stmt = gsi_stmt (gsi);
3261           bitmap read_avail = READ_AVAIL_IN (bb);
3262           bitmap store_avail = STORE_AVAIL_IN (bb);
3263           bitmap store_antic = STORE_ANTIC_OUT (bb);
3264           unsigned int loc;
3265
3266           if (is_tm_simple_load (stmt))
3267             {
3268               loc = tm_memopt_value_number (stmt, NO_INSERT);
3269               if (store_avail && bitmap_bit_p (store_avail, loc))
3270                 tm_memopt_transform_stmt (TRANSFORM_RAW, stmt, &gsi);
3271               else if (store_antic && bitmap_bit_p (store_antic, loc))
3272                 {
3273                   tm_memopt_transform_stmt (TRANSFORM_RFW, stmt, &gsi);
3274                   bitmap_set_bit (store_avail, loc);
3275                 }
3276               else if (read_avail && bitmap_bit_p (read_avail, loc))
3277                 tm_memopt_transform_stmt (TRANSFORM_RAR, stmt, &gsi);
3278               else
3279                 bitmap_set_bit (read_avail, loc);
3280             }
3281           else if (is_tm_simple_store (stmt))
3282             {
3283               loc = tm_memopt_value_number (stmt, NO_INSERT);
3284               if (store_avail && bitmap_bit_p (store_avail, loc))
3285                 tm_memopt_transform_stmt (TRANSFORM_WAW, stmt, &gsi);
3286               else
3287                 {
3288                   if (read_avail && bitmap_bit_p (read_avail, loc))
3289                     tm_memopt_transform_stmt (TRANSFORM_WAR, stmt, &gsi);
3290                   bitmap_set_bit (store_avail, loc);
3291                 }
3292             }
3293         }
3294     }
3295 }
3296
3297 /* Return a new set of bitmaps for a BB.  */
3298
3299 static struct tm_memopt_bitmaps *
3300 tm_memopt_init_sets (void)
3301 {
3302   struct tm_memopt_bitmaps *b
3303     = XOBNEW (&tm_memopt_obstack.obstack, struct tm_memopt_bitmaps);
3304   b->store_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3305   b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3306   b->store_antic_in = BITMAP_ALLOC (&tm_memopt_obstack);
3307   b->store_antic_out = BITMAP_ALLOC (&tm_memopt_obstack);
3308   b->store_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3309   b->read_avail_in = BITMAP_ALLOC (&tm_memopt_obstack);
3310   b->read_avail_out = BITMAP_ALLOC (&tm_memopt_obstack);
3311   b->read_local = BITMAP_ALLOC (&tm_memopt_obstack);
3312   b->store_local = BITMAP_ALLOC (&tm_memopt_obstack);
3313   return b;
3314 }
3315
3316 /* Free sets computed for each BB.  */
3317
3318 static void
3319 tm_memopt_free_sets (VEC (basic_block, heap) *blocks)
3320 {
3321   size_t i;
3322   basic_block bb;
3323
3324   for (i = 0; VEC_iterate (basic_block, blocks, i, bb); ++i)
3325     bb->aux = NULL;
3326 }
3327
3328 /* Clear the visited bit for every basic block in BLOCKS.  */
3329
3330 static void
3331 tm_memopt_clear_visited (VEC (basic_block, heap) *blocks)
3332 {
3333   size_t i;
3334   basic_block bb;
3335
3336   for (i = 0; VEC_iterate (basic_block, blocks, i, bb); ++i)
3337     BB_VISITED_P (bb) = false;
3338 }
3339
3340 /* Replace TM load/stores with hints for the runtime.  We handle
3341    things like read-after-write, write-after-read, read-after-read,
3342    read-for-write, etc.  */
3343
3344 static unsigned int
3345 execute_tm_memopt (void)
3346 {
3347   struct tm_region *region;
3348   VEC (basic_block, heap) *bbs;
3349
3350   tm_memopt_value_id = 0;
3351   tm_memopt_value_numbers = htab_create (10, tm_memop_hash, tm_memop_eq, free);
3352
3353   for (region = all_tm_regions; region; region = region->next)
3354     {
3355       /* All the TM stores/loads in the current region.  */
3356       size_t i;
3357       basic_block bb;
3358
3359       bitmap_obstack_initialize (&tm_memopt_obstack);
3360
3361       /* Save all BBs for the current region.  */
3362       bbs = get_tm_region_blocks (region->entry_block,
3363                                   region->exit_blocks,
3364                                   region->irr_blocks,
3365                                   NULL,
3366                                   false);
3367
3368       /* Collect all the memory operations.  */
3369       for (i = 0; VEC_iterate (basic_block, bbs, i, bb); ++i)
3370         {
3371           bb->aux = tm_memopt_init_sets ();
3372           tm_memopt_accumulate_memops (bb);
3373         }
3374
3375       /* Solve data flow equations and transform each block accordingly.  */
3376       tm_memopt_clear_visited (bbs);
3377       tm_memopt_compute_available (region, bbs);
3378       tm_memopt_clear_visited (bbs);
3379       tm_memopt_compute_antic (region, bbs);
3380       tm_memopt_transform_blocks (bbs);
3381
3382       tm_memopt_free_sets (bbs);
3383       VEC_free (basic_block, heap, bbs);
3384       bitmap_obstack_release (&tm_memopt_obstack);
3385       htab_empty (tm_memopt_value_numbers);
3386     }
3387
3388   htab_delete (tm_memopt_value_numbers);
3389   return 0;
3390 }
3391
3392 static bool
3393 gate_tm_memopt (void)
3394 {
3395   return flag_tm && optimize > 0;
3396 }
3397
3398 struct gimple_opt_pass pass_tm_memopt =
3399 {
3400  {
3401   GIMPLE_PASS,
3402   "tmmemopt",                           /* name */
3403   gate_tm_memopt,                       /* gate */
3404   execute_tm_memopt,                    /* execute */
3405   NULL,                                 /* sub */
3406   NULL,                                 /* next */
3407   0,                                    /* static_pass_number */
3408   TV_TRANS_MEM,                         /* tv_id */
3409   PROP_ssa | PROP_cfg,                  /* properties_required */
3410   0,                                    /* properties_provided */
3411   0,                                    /* properties_destroyed */
3412   0,                                    /* todo_flags_start */
3413   TODO_dump_func,                       /* todo_flags_finish */
3414  }
3415 };
3416
3417 \f
3418 /* Interprocedual analysis for the creation of transactional clones.
3419    The aim of this pass is to find which functions are referenced in
3420    a non-irrevocable transaction context, and for those over which
3421    we have control (or user directive), create a version of the
3422    function which uses only the transactional interface to reference
3423    protected memories.  This analysis proceeds in several steps:
3424
3425      (1) Collect the set of all possible transactional clones:
3426
3427         (a) For all local public functions marked tm_callable, push
3428             it onto the tm_callee queue.
3429
3430         (b) For all local functions, scan for calls in transaction blocks.
3431             Push the caller and callee onto the tm_caller and tm_callee
3432             queues.  Count the number of callers for each callee.
3433
3434         (c) For each local function on the callee list, assume we will
3435             create a transactional clone.  Push *all* calls onto the
3436             callee queues; count the number of clone callers separately
3437             to the number of original callers.
3438
3439      (2) Propagate irrevocable status up the dominator tree:
3440
3441         (a) Any external function on the callee list that is not marked
3442             tm_callable is irrevocable.  Push all callers of such onto
3443             a worklist.
3444
3445         (b) For each function on the worklist, mark each block that
3446             contains an irrevocable call.  Use the AND operator to
3447             propagate that mark up the dominator tree.
3448
3449         (c) If we reach the entry block for a possible transactional
3450             clone, then the transactional clone is irrevocable, and
3451             we should not create the clone after all.  Push all
3452             callers onto the worklist.
3453
3454         (d) Place tm_irrevocable calls at the beginning of the relevant
3455             blocks.  Special case here is the entry block for the entire
3456             transaction region; there we mark it GTMA_DOES_GO_IRREVOCABLE for
3457             the library to begin the region in serial mode.  Decrement
3458             the call count for all callees in the irrevocable region.
3459
3460      (3) Create the transactional clones:
3461
3462         Any tm_callee that still has a non-zero call count is cloned.
3463 */
3464
3465 /* This structure is stored in the AUX field of each cgraph_node.  */
3466 struct tm_ipa_cg_data
3467 {
3468   /* The clone of the function that got created.  */
3469   struct cgraph_node *clone;
3470
3471   /* The tm regions in the normal function.  */
3472   struct tm_region *all_tm_regions;
3473
3474   /* The blocks of the normal/clone functions that contain irrevocable
3475      calls, or blocks that are post-dominated by irrevocable calls.  */
3476   bitmap irrevocable_blocks_normal;
3477   bitmap irrevocable_blocks_clone;
3478
3479   /* The blocks of the normal function that are involved in transactions.  */
3480   bitmap transaction_blocks_normal;
3481
3482   /* The number of callers to the transactional clone of this function
3483      from normal and transactional clones respectively.  */
3484   unsigned tm_callers_normal;
3485   unsigned tm_callers_clone;
3486
3487   /* True if all calls to this function's transactional clone
3488      are irrevocable.  Also automatically true if the function
3489      has no transactional clone.  */
3490   bool is_irrevocable;
3491
3492   /* Flags indicating the presence of this function in various queues.  */
3493   bool in_callee_queue;
3494   bool in_worklist;
3495
3496   /* Flags indicating the kind of scan desired while in the worklist.  */
3497   bool want_irr_scan_normal;
3498 };
3499
3500 typedef struct cgraph_node *cgraph_node_p;
3501
3502 DEF_VEC_P (cgraph_node_p);
3503 DEF_VEC_ALLOC_P (cgraph_node_p, heap);
3504
3505 typedef VEC (cgraph_node_p, heap) *cgraph_node_queue;
3506
3507 /* Return the ipa data associated with NODE, allocating zeroed memory
3508    if necessary.  */
3509
3510 static struct tm_ipa_cg_data *
3511 get_cg_data (struct cgraph_node *node)
3512 {
3513   struct tm_ipa_cg_data *d = (struct tm_ipa_cg_data *) node->aux;
3514
3515   if (d == NULL)
3516     {
3517       d = (struct tm_ipa_cg_data *)
3518         obstack_alloc (&tm_obstack.obstack, sizeof (*d));
3519       node->aux = (void *) d;
3520       memset (d, 0, sizeof (*d));
3521     }
3522
3523   return d;
3524 }
3525
3526 /* Add NODE to the end of QUEUE, unless IN_QUEUE_P indicates that
3527    it is already present.  */
3528
3529 static void
3530 maybe_push_queue (struct cgraph_node *node,
3531                   cgraph_node_queue *queue_p, bool *in_queue_p)
3532 {
3533   if (!*in_queue_p)
3534     {
3535       *in_queue_p = true;
3536       VEC_safe_push (cgraph_node_p, heap, *queue_p, node);
3537     }
3538 }
3539
3540 /* A subroutine of ipa_tm_scan_calls_transaction and ipa_tm_scan_calls_clone.
3541    Queue all callees within block BB.  */
3542
3543 static void
3544 ipa_tm_scan_calls_block (cgraph_node_queue *callees_p,
3545                          basic_block bb, bool for_clone)
3546 {
3547   gimple_stmt_iterator gsi;
3548
3549   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3550     {
3551       gimple stmt = gsi_stmt (gsi);
3552       if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
3553         {
3554           tree fndecl = gimple_call_fndecl (stmt);
3555           if (fndecl)
3556             {
3557               struct tm_ipa_cg_data *d;
3558               unsigned *pcallers;
3559               struct cgraph_node *node;
3560
3561               if (is_tm_ending_fndecl (fndecl))
3562                 continue;
3563               if (find_tm_replacement_function (fndecl))
3564                 continue;
3565
3566               node = cgraph_get_node (fndecl);
3567               gcc_assert (node != NULL);
3568               d = get_cg_data (node);
3569
3570               pcallers = (for_clone ? &d->tm_callers_clone
3571                           : &d->tm_callers_normal);
3572               *pcallers += 1;
3573
3574               maybe_push_queue (node, callees_p, &d->in_callee_queue);
3575             }
3576         }
3577     }
3578 }
3579
3580 /* Scan all calls in NODE that are within a transaction region,
3581    and push the resulting nodes into the callee queue.  */
3582
3583 static void
3584 ipa_tm_scan_calls_transaction (struct tm_ipa_cg_data *d,
3585                                cgraph_node_queue *callees_p)
3586 {
3587   struct tm_region *r;
3588
3589   d->transaction_blocks_normal = BITMAP_ALLOC (&tm_obstack);
3590   d->all_tm_regions = all_tm_regions;
3591
3592   for (r = all_tm_regions; r; r = r->next)
3593     {
3594       VEC (basic_block, heap) *bbs;
3595       basic_block bb;
3596       unsigned i;
3597
3598       bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks, NULL,
3599                                   d->transaction_blocks_normal, false);
3600
3601       FOR_EACH_VEC_ELT (basic_block, bbs, i, bb)
3602         ipa_tm_scan_calls_block (callees_p, bb, false);
3603
3604       VEC_free (basic_block, heap, bbs);
3605     }
3606 }
3607
3608 /* Scan all calls in NODE as if this is the transactional clone,
3609    and push the destinations into the callee queue.  */
3610
3611 static void
3612 ipa_tm_scan_calls_clone (struct cgraph_node *node,
3613                          cgraph_node_queue *callees_p)
3614 {
3615   struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3616   basic_block bb;
3617
3618   FOR_EACH_BB_FN (bb, fn)
3619     ipa_tm_scan_calls_block (callees_p, bb, true);
3620 }
3621
3622 /* The function NODE has been detected to be irrevocable.  Push all
3623    of its callers onto WORKLIST for the purpose of re-scanning them.  */
3624
3625 static void
3626 ipa_tm_note_irrevocable (struct cgraph_node *node,
3627                          cgraph_node_queue *worklist_p)
3628 {
3629   struct tm_ipa_cg_data *d = get_cg_data (node);
3630   struct cgraph_edge *e;
3631
3632   d->is_irrevocable = true;
3633
3634   for (e = node->callers; e ; e = e->next_caller)
3635     {
3636       basic_block bb;
3637
3638       /* Don't examine recursive calls.  */
3639       if (e->caller == node)
3640         continue;
3641       /* Even if we think we can go irrevocable, believe the user
3642          above all.  */
3643       if (is_tm_safe_or_pure (e->caller->decl))
3644         continue;
3645
3646       d = get_cg_data (e->caller);
3647
3648       /* Check if the callee is in a transactional region.  If so,
3649          schedule the function for normal re-scan as well.  */
3650       bb = gimple_bb (e->call_stmt);
3651       gcc_assert (bb != NULL);
3652       if (d->transaction_blocks_normal
3653           && bitmap_bit_p (d->transaction_blocks_normal, bb->index))
3654         d->want_irr_scan_normal = true;
3655
3656       maybe_push_queue (e->caller, worklist_p, &d->in_worklist);
3657     }
3658 }
3659
3660 /* A subroutine of ipa_tm_scan_irr_blocks; return true iff any statement
3661    within the block is irrevocable.  */
3662
3663 static bool
3664 ipa_tm_scan_irr_block (basic_block bb)
3665 {
3666   gimple_stmt_iterator gsi;
3667   tree fn;
3668
3669   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3670     {
3671       gimple stmt = gsi_stmt (gsi);
3672       switch (gimple_code (stmt))
3673         {
3674         case GIMPLE_CALL:
3675           if (is_tm_pure_call (stmt))
3676             break;
3677
3678           fn = gimple_call_fn (stmt);
3679
3680           /* Functions with the attribute are by definition irrevocable.  */
3681           if (is_tm_irrevocable (fn))
3682             return true;
3683
3684           /* For direct function calls, go ahead and check for replacement
3685              functions, or transitive irrevocable functions.  For indirect
3686              functions, we'll ask the runtime.  */
3687           if (TREE_CODE (fn) == ADDR_EXPR)
3688             {
3689               struct tm_ipa_cg_data *d;
3690
3691               fn = TREE_OPERAND (fn, 0);
3692               if (is_tm_ending_fndecl (fn))
3693                 break;
3694               if (find_tm_replacement_function (fn))
3695                 break;
3696
3697               d = get_cg_data (cgraph_get_node (fn));
3698               if (d->is_irrevocable)
3699                 return true;
3700             }
3701           break;
3702
3703         case GIMPLE_ASM:
3704           /* ??? The Approved Method of indicating that an inline
3705              assembly statement is not relevant to the transaction
3706              is to wrap it in a __tm_waiver block.  This is not
3707              yet implemented, so we can't check for it.  */
3708           return true;
3709
3710         default:
3711           break;
3712         }
3713     }
3714
3715   return false;
3716 }
3717
3718 /* For each of the blocks seeded witin PQUEUE, walk the CFG looking
3719    for new irrevocable blocks, marking them in NEW_IRR.  Don't bother
3720    scanning past OLD_IRR or EXIT_BLOCKS.  */
3721
3722 static bool
3723 ipa_tm_scan_irr_blocks (VEC (basic_block, heap) **pqueue, bitmap new_irr,
3724                         bitmap old_irr, bitmap exit_blocks)
3725 {
3726   bool any_new_irr = false;
3727   edge e;
3728   edge_iterator ei;
3729   bitmap visited_blocks = BITMAP_ALLOC (NULL);
3730
3731   do
3732     {
3733       basic_block bb = VEC_pop (basic_block, *pqueue);
3734
3735       /* Don't re-scan blocks we know already are irrevocable.  */
3736       if (old_irr && bitmap_bit_p (old_irr, bb->index))
3737         continue;
3738
3739       if (ipa_tm_scan_irr_block (bb))
3740         {
3741           bitmap_set_bit (new_irr, bb->index);
3742           any_new_irr = true;
3743         }
3744       else if (exit_blocks == NULL || !bitmap_bit_p (exit_blocks, bb->index))
3745         {
3746           FOR_EACH_EDGE (e, ei, bb->succs)
3747             if (!bitmap_bit_p (visited_blocks, e->dest->index))
3748               {
3749                 bitmap_set_bit (visited_blocks, e->dest->index);
3750                 VEC_safe_push (basic_block, heap, *pqueue, e->dest);
3751               }
3752         }
3753     }
3754   while (!VEC_empty (basic_block, *pqueue));
3755
3756   BITMAP_FREE (visited_blocks);
3757
3758   return any_new_irr;
3759 }
3760
3761 /* Propagate the irrevocable property both up and down the dominator tree.
3762    BB is the current block being scanned; EXIT_BLOCKS are the edges of the
3763    TM regions; OLD_IRR are the results of a previous scan of the dominator
3764    tree which has been fully propagated; NEW_IRR is the set of new blocks
3765    which are gaining the irrevocable property during the current scan.  */
3766
3767 static void
3768 ipa_tm_propagate_irr (basic_block entry_block, bitmap new_irr,
3769                       bitmap old_irr, bitmap exit_blocks)
3770 {
3771   VEC (basic_block, heap) *bbs;
3772   bitmap all_region_blocks;
3773
3774   /* If this block is in the old set, no need to rescan.  */
3775   if (old_irr && bitmap_bit_p (old_irr, entry_block->index))
3776     return;
3777
3778   all_region_blocks = BITMAP_ALLOC (&tm_obstack);
3779   bbs = get_tm_region_blocks (entry_block, exit_blocks, NULL,
3780                               all_region_blocks, false);
3781   do
3782     {
3783       basic_block bb = VEC_pop (basic_block, bbs);
3784       bool this_irr = bitmap_bit_p (new_irr, bb->index);
3785       bool all_son_irr = false;
3786       edge_iterator ei;
3787       edge e;
3788
3789       /* Propagate up.  If my children are, I am too, but we must have
3790          at least one child that is.  */
3791       if (!this_irr)
3792         {
3793           FOR_EACH_EDGE (e, ei, bb->succs)
3794             {
3795               if (!bitmap_bit_p (new_irr, e->dest->index))
3796                 {
3797                   all_son_irr = false;
3798                   break;
3799                 }
3800               else
3801                 all_son_irr = true;
3802             }
3803           if (all_son_irr)
3804             {
3805               /* Add block to new_irr if it hasn't already been processed. */
3806               if (!old_irr || !bitmap_bit_p (old_irr, bb->index))
3807                 {
3808                   bitmap_set_bit (new_irr, bb->index);
3809                   this_irr = true;
3810                 }
3811             }
3812         }
3813
3814       /* Propagate down to everyone we immediately dominate.  */
3815       if (this_irr)
3816         {
3817           basic_block son;
3818           for (son = first_dom_son (CDI_DOMINATORS, bb);
3819                son;
3820                son = next_dom_son (CDI_DOMINATORS, son))
3821             {
3822               /* Make sure block is actually in a TM region, and it
3823                  isn't already in old_irr.  */
3824               if ((!old_irr || !bitmap_bit_p (old_irr, son->index))
3825                   && bitmap_bit_p (all_region_blocks, son->index))
3826                 bitmap_set_bit (new_irr, son->index);
3827             }
3828         }
3829     }
3830   while (!VEC_empty (basic_block, bbs));
3831
3832   BITMAP_FREE (all_region_blocks);
3833   VEC_free (basic_block, heap, bbs);
3834 }
3835
3836 static void
3837 ipa_tm_decrement_clone_counts (basic_block bb, bool for_clone)
3838 {
3839   gimple_stmt_iterator gsi;
3840
3841   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3842     {
3843       gimple stmt = gsi_stmt (gsi);
3844       if (is_gimple_call (stmt) && !is_tm_pure_call (stmt))
3845         {
3846           tree fndecl = gimple_call_fndecl (stmt);
3847           if (fndecl)
3848             {
3849               struct tm_ipa_cg_data *d;
3850               unsigned *pcallers;
3851
3852               if (is_tm_ending_fndecl (fndecl))
3853                 continue;
3854               if (find_tm_replacement_function (fndecl))
3855                 continue;
3856
3857               d = get_cg_data (cgraph_get_node (fndecl));
3858               pcallers = (for_clone ? &d->tm_callers_clone
3859                           : &d->tm_callers_normal);
3860
3861               gcc_assert (*pcallers > 0);
3862               *pcallers -= 1;
3863             }
3864         }
3865     }
3866 }
3867
3868 /* (Re-)Scan the transaction blocks in NODE for calls to irrevocable functions,
3869    as well as other irrevocable actions such as inline assembly.  Mark all
3870    such blocks as irrevocable and decrement the number of calls to
3871    transactional clones.  Return true if, for the transactional clone, the
3872    entire function is irrevocable.  */
3873
3874 static bool
3875 ipa_tm_scan_irr_function (struct cgraph_node *node, bool for_clone)
3876 {
3877   struct tm_ipa_cg_data *d;
3878   bitmap new_irr, old_irr;
3879   VEC (basic_block, heap) *queue;
3880   bool ret = false;
3881
3882   current_function_decl = node->decl;
3883   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
3884   calculate_dominance_info (CDI_DOMINATORS);
3885
3886   d = get_cg_data (node);
3887   queue = VEC_alloc (basic_block, heap, 10);
3888   new_irr = BITMAP_ALLOC (&tm_obstack);
3889
3890   /* Scan each tm region, propagating irrevocable status through the tree.  */
3891   if (for_clone)
3892     {
3893       old_irr = d->irrevocable_blocks_clone;
3894       VEC_quick_push (basic_block, queue, single_succ (ENTRY_BLOCK_PTR));
3895       if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr, NULL))
3896         {
3897           ipa_tm_propagate_irr (single_succ (ENTRY_BLOCK_PTR), new_irr,
3898                                 old_irr, NULL);
3899           ret = bitmap_bit_p (new_irr, single_succ (ENTRY_BLOCK_PTR)->index);
3900         }
3901     }
3902   else
3903     {
3904       struct tm_region *region;
3905
3906       old_irr = d->irrevocable_blocks_normal;
3907       for (region = d->all_tm_regions; region; region = region->next)
3908         {
3909           VEC_quick_push (basic_block, queue, region->entry_block);
3910           if (ipa_tm_scan_irr_blocks (&queue, new_irr, old_irr,
3911                                       region->exit_blocks))
3912             ipa_tm_propagate_irr (region->entry_block, new_irr, old_irr,
3913                                   region->exit_blocks);
3914         }
3915     }
3916
3917   /* If we found any new irrevocable blocks, reduce the call count for
3918      transactional clones within the irrevocable blocks.  Save the new
3919      set of irrevocable blocks for next time.  */
3920   if (!bitmap_empty_p (new_irr))
3921     {
3922       bitmap_iterator bmi;
3923       unsigned i;
3924
3925       EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
3926         ipa_tm_decrement_clone_counts (BASIC_BLOCK (i), for_clone);
3927
3928       if (old_irr)
3929         {
3930           bitmap_ior_into (old_irr, new_irr);
3931           BITMAP_FREE (new_irr);
3932         }
3933       else if (for_clone)
3934         d->irrevocable_blocks_clone = new_irr;
3935       else
3936         d->irrevocable_blocks_normal = new_irr;
3937
3938       if (dump_file && new_irr)
3939         {
3940           const char *dname;
3941           bitmap_iterator bmi;
3942           unsigned i;
3943
3944           dname = lang_hooks.decl_printable_name (current_function_decl, 2);
3945           EXECUTE_IF_SET_IN_BITMAP (new_irr, 0, i, bmi)
3946             fprintf (dump_file, "%s: bb %d goes irrevocable\n", dname, i);
3947         }
3948     }
3949   else
3950     BITMAP_FREE (new_irr);
3951
3952   VEC_free (basic_block, heap, queue);
3953   pop_cfun ();
3954   current_function_decl = NULL;
3955
3956   return ret;
3957 }
3958
3959 /* Return true if, for the transactional clone of NODE, any call
3960    may enter irrevocable mode.  */
3961
3962 static bool
3963 ipa_tm_mayenterirr_function (struct cgraph_node *node)
3964 {
3965   struct tm_ipa_cg_data *d = get_cg_data (node);
3966   tree decl = node->decl;
3967   unsigned flags = flags_from_decl_or_type (decl);
3968
3969   /* Handle some TM builtins.  Ordinarily these aren't actually generated
3970      at this point, but handling these functions when written in by the
3971      user makes it easier to build unit tests.  */
3972   if (flags & ECF_TM_BUILTIN)
3973     return false;
3974
3975   /* Filter out all functions that are marked.  */
3976   if (flags & ECF_TM_PURE)
3977     return false;
3978   if (is_tm_safe (decl))
3979     return false;
3980   if (is_tm_irrevocable (decl))
3981     return true;
3982   if (is_tm_callable (decl))
3983     return true;
3984   if (find_tm_replacement_function (decl))
3985     return true;
3986
3987   /* If we aren't seeing the final version of the function we don't
3988      know what it will contain at runtime.  */
3989   if (cgraph_function_body_availability (node) < AVAIL_AVAILABLE)
3990     return true;
3991
3992   /* If the function must go irrevocable, then of course true.  */
3993   if (d->is_irrevocable)
3994     return true;
3995
3996   /* If there are any blocks marked irrevocable, then the function
3997      as a whole may enter irrevocable.  */
3998   if (d->irrevocable_blocks_clone)
3999     return true;
4000
4001   /* We may have previously marked this function as tm_may_enter_irr;
4002      see pass_diagnose_tm_blocks.  */
4003   if (node->local.tm_may_enter_irr)
4004     return true;
4005
4006   /* Recurse on the main body for aliases.  In general, this will
4007      result in one of the bits above being set so that we will not
4008      have to recurse next time.  */
4009   if (node->alias)
4010     return ipa_tm_mayenterirr_function (cgraph_get_node (node->thunk.alias));
4011
4012   /* What remains is unmarked local functions without items that force
4013      the function to go irrevocable.  */
4014   return false;
4015 }
4016
4017 /* Diagnose calls from transaction_safe functions to unmarked
4018    functions that are determined to not be safe.  */
4019
4020 static void
4021 ipa_tm_diagnose_tm_safe (struct cgraph_node *node)
4022 {
4023   struct cgraph_edge *e;
4024
4025   for (e = node->callees; e ; e = e->next_callee)
4026     if (!is_tm_callable (e->callee->decl)
4027         && e->callee->local.tm_may_enter_irr)
4028       error_at (gimple_location (e->call_stmt),
4029                 "unsafe function call %qD within "
4030                 "%<transaction_safe%> function", e->callee->decl);
4031 }
4032
4033 /* Diagnose call from atomic transactions to unmarked functions
4034    that are determined to not be safe.  */
4035
4036 static void
4037 ipa_tm_diagnose_transaction (struct cgraph_node *node,
4038                            struct tm_region *all_tm_regions)
4039 {
4040   struct tm_region *r;
4041
4042   for (r = all_tm_regions; r ; r = r->next)
4043     if (gimple_transaction_subcode (r->transaction_stmt) & GTMA_IS_RELAXED)
4044       {
4045         /* Atomic transactions can be nested inside relaxed.  */
4046         if (r->inner)
4047           ipa_tm_diagnose_transaction (node, r->inner);
4048       }
4049     else
4050       {
4051         VEC (basic_block, heap) *bbs;
4052         gimple_stmt_iterator gsi;
4053         basic_block bb;
4054         size_t i;
4055
4056         bbs = get_tm_region_blocks (r->entry_block, r->exit_blocks,
4057                                     r->irr_blocks, NULL, false);
4058
4059         for (i = 0; VEC_iterate (basic_block, bbs, i, bb); ++i)
4060           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4061             {
4062               gimple stmt = gsi_stmt (gsi);
4063               tree fndecl;
4064
4065               if (gimple_code (stmt) == GIMPLE_ASM)
4066                 {
4067                   error_at (gimple_location (stmt),
4068                             "asm not allowed in atomic transaction");
4069                   continue;
4070                 }
4071
4072               if (!is_gimple_call (stmt))
4073                 continue;
4074               fndecl = gimple_call_fndecl (stmt);
4075
4076               /* Indirect function calls have been diagnosed already.  */
4077               if (!fndecl)
4078                 continue;
4079
4080               /* Stop at the end of the transaction.  */
4081               if (is_tm_ending_fndecl (fndecl))
4082                 {
4083                   if (bitmap_bit_p (r->exit_blocks, bb->index))
4084                     break;
4085                   continue;
4086                 }
4087
4088               /* Marked functions have been diagnosed already.  */
4089               if (is_tm_pure_call (stmt))
4090                 continue;
4091               if (is_tm_callable (fndecl))
4092                 continue;
4093
4094               if (cgraph_local_info (fndecl)->tm_may_enter_irr)
4095                 error_at (gimple_location (stmt),
4096                           "unsafe function call %qD within "
4097                           "atomic transaction", fndecl);
4098             }
4099
4100         VEC_free (basic_block, heap, bbs);
4101       }
4102 }
4103
4104 /* Return a transactional mangled name for the DECL_ASSEMBLER_NAME in
4105    OLD_DECL.  The returned value is a freshly malloced pointer that
4106    should be freed by the caller.  */
4107
4108 static tree
4109 tm_mangle (tree old_asm_id)
4110 {
4111   const char *old_asm_name;
4112   char *tm_name;
4113   void *alloc = NULL;
4114   struct demangle_component *dc;
4115   tree new_asm_id;
4116
4117   /* Determine if the symbol is already a valid C++ mangled name.  Do this
4118      even for C, which might be interfacing with C++ code via appropriately
4119      ugly identifiers.  */
4120   /* ??? We could probably do just as well checking for "_Z" and be done.  */
4121   old_asm_name = IDENTIFIER_POINTER (old_asm_id);
4122   dc = cplus_demangle_v3_components (old_asm_name, DMGL_NO_OPTS, &alloc);
4123
4124   if (dc == NULL)
4125     {
4126       char length[8];
4127
4128     do_unencoded:
4129       sprintf (length, "%u", IDENTIFIER_LENGTH (old_asm_id));
4130       tm_name = concat ("_ZGTt", length, old_asm_name, NULL);
4131     }
4132   else
4133     {
4134       old_asm_name += 2;        /* Skip _Z */
4135
4136       switch (dc->type)
4137         {
4138         case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4139         case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4140           /* Don't play silly games, you!  */
4141           goto do_unencoded;
4142
4143         case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4144           /* I'd really like to know if we can ever be passed one of
4145              these from the C++ front end.  The Logical Thing would
4146              seem that hidden-alias should be outer-most, so that we
4147              get hidden-alias of a transaction-clone and not vice-versa.  */
4148           old_asm_name += 2;
4149           break;
4150
4151         default:
4152           break;
4153         }
4154
4155       tm_name = concat ("_ZGTt", old_asm_name, NULL);
4156     }
4157   free (alloc);
4158
4159   new_asm_id = get_identifier (tm_name);
4160   free (tm_name);
4161
4162   return new_asm_id;
4163 }
4164
4165 static inline void
4166 ipa_tm_mark_needed_node (struct cgraph_node *node)
4167 {
4168   cgraph_mark_needed_node (node);
4169   /* ??? function_and_variable_visibility will reset
4170      the needed bit, without actually checking.  */
4171   node->analyzed = 1;
4172 }
4173
4174 /* Callback data for ipa_tm_create_version_alias.  */
4175 struct create_version_alias_info
4176 {
4177   struct cgraph_node *old_node;
4178   tree new_decl;
4179 };
4180
4181 /* A subrontine of ipa_tm_create_version, called via
4182    cgraph_for_node_and_aliases.  Create new tm clones for each of
4183    the existing aliases.  */
4184 static bool
4185 ipa_tm_create_version_alias (struct cgraph_node *node, void *data)
4186 {
4187   struct create_version_alias_info *info
4188     = (struct create_version_alias_info *)data;
4189   tree old_decl, new_decl, tm_name;
4190   struct cgraph_node *new_node;
4191
4192   if (!node->same_body_alias)
4193     return false;
4194
4195   old_decl = node->decl;
4196   tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4197   new_decl = build_decl (DECL_SOURCE_LOCATION (old_decl),
4198                          TREE_CODE (old_decl), tm_name,
4199                          TREE_TYPE (old_decl));
4200
4201   SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4202   SET_DECL_RTL (new_decl, NULL);
4203
4204   /* Based loosely on C++'s make_alias_for().  */
4205   TREE_PUBLIC (new_decl) = TREE_PUBLIC (old_decl);
4206   DECL_CONTEXT (new_decl) = NULL;
4207   TREE_READONLY (new_decl) = TREE_READONLY (old_decl);
4208   DECL_EXTERNAL (new_decl) = 0;
4209   DECL_ARTIFICIAL (new_decl) = 1;
4210   TREE_ADDRESSABLE (new_decl) = 1;
4211   TREE_USED (new_decl) = 1;
4212   TREE_SYMBOL_REFERENCED (tm_name) = 1;
4213
4214   /* Perform the same remapping to the comdat group.  */
4215   if (DECL_COMDAT (new_decl))
4216     DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4217
4218   new_node = cgraph_same_body_alias (NULL, new_decl, info->new_decl);
4219   new_node->tm_clone = true;
4220   get_cg_data (node)->clone = new_node;
4221
4222   record_tm_clone_pair (old_decl, new_decl);
4223
4224   if (info->old_node->needed)
4225     ipa_tm_mark_needed_node (new_node);
4226   return false;
4227 }
4228
4229 /* Create a copy of the function (possibly declaration only) of OLD_NODE,
4230    appropriate for the transactional clone.  */
4231
4232 static void
4233 ipa_tm_create_version (struct cgraph_node *old_node)
4234 {
4235   tree new_decl, old_decl, tm_name;
4236   struct cgraph_node *new_node;
4237
4238   old_decl = old_node->decl;
4239   new_decl = copy_node (old_decl);
4240
4241   /* DECL_ASSEMBLER_NAME needs to be set before we call
4242      cgraph_copy_node_for_versioning below, because cgraph_node will
4243      fill the assembler_name_hash.  */
4244   tm_name = tm_mangle (DECL_ASSEMBLER_NAME (old_decl));
4245   SET_DECL_ASSEMBLER_NAME (new_decl, tm_name);
4246   SET_DECL_RTL (new_decl, NULL);
4247   TREE_SYMBOL_REFERENCED (tm_name) = 1;
4248
4249   /* Perform the same remapping to the comdat group.  */
4250   if (DECL_COMDAT (new_decl))
4251     DECL_COMDAT_GROUP (new_decl) = tm_mangle (DECL_COMDAT_GROUP (old_decl));
4252
4253   new_node = cgraph_copy_node_for_versioning (old_node, new_decl, NULL, NULL);
4254   new_node->lowered = true;
4255   new_node->tm_clone = 1;
4256   get_cg_data (old_node)->clone = new_node;
4257
4258   if (cgraph_function_body_availability (old_node) >= AVAIL_OVERWRITABLE)
4259     {
4260       /* Remap extern inline to static inline.  */
4261       /* ??? Is it worth trying to use make_decl_one_only?  */
4262       if (DECL_DECLARED_INLINE_P (new_decl) && DECL_EXTERNAL (new_decl))
4263         {
4264           DECL_EXTERNAL (new_decl) = 0;
4265           TREE_PUBLIC (new_decl) = 0;
4266         }
4267
4268       tree_function_versioning (old_decl, new_decl, NULL, false, NULL,
4269                                 NULL, NULL);
4270     }
4271
4272   record_tm_clone_pair (old_decl, new_decl);
4273
4274   cgraph_call_function_insertion_hooks (new_node);
4275   if (old_node->needed)
4276     ipa_tm_mark_needed_node (new_node);
4277
4278   /* Do the same thing, but for any aliases of the original node.  */
4279   {
4280     struct create_version_alias_info data;
4281     data.old_node = old_node;
4282     data.new_decl = new_decl;
4283     cgraph_for_node_and_aliases (old_node, ipa_tm_create_version_alias,
4284                                  &data, true);
4285   }
4286 }
4287
4288 /* Construct a call to TM_IRREVOCABLE and insert it at the beginning of BB.  */
4289
4290 static void
4291 ipa_tm_insert_irr_call (struct cgraph_node *node, struct tm_region *region,
4292                         basic_block bb)
4293 {
4294   gimple_stmt_iterator gsi;
4295   gimple g;
4296
4297   transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4298
4299   g = gimple_build_call (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE),
4300                          1, build_int_cst (NULL_TREE, MODE_SERIALIRREVOCABLE));
4301
4302   split_block_after_labels (bb);
4303   gsi = gsi_after_labels (bb);
4304   gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4305
4306   cgraph_create_edge (node,
4307                cgraph_get_create_node
4308                   (builtin_decl_explicit (BUILT_IN_TM_IRREVOCABLE)),
4309                       g, 0,
4310                       compute_call_stmt_bb_frequency (node->decl,
4311                                                       gimple_bb (g)));
4312 }
4313
4314 /* Construct a call to TM_GETTMCLONE and insert it before GSI.  */
4315
4316 static bool
4317 ipa_tm_insert_gettmclone_call (struct cgraph_node *node,
4318                                struct tm_region *region,
4319                                gimple_stmt_iterator *gsi, gimple stmt)
4320 {
4321   tree gettm_fn, ret, old_fn, callfn;
4322   gimple g, g2;
4323   bool safe;
4324
4325   old_fn = gimple_call_fn (stmt);
4326
4327   if (TREE_CODE (old_fn) == ADDR_EXPR)
4328     {
4329       tree fndecl = TREE_OPERAND (old_fn, 0);
4330       tree clone = get_tm_clone_pair (fndecl);
4331
4332       /* By transforming the call into a TM_GETTMCLONE, we are
4333          technically taking the address of the original function and
4334          its clone.  Explain this so inlining will know this function
4335          is needed.  */
4336       cgraph_mark_address_taken_node (cgraph_get_node (fndecl));
4337       if (clone)
4338         cgraph_mark_address_taken_node (cgraph_get_node (clone));
4339     }
4340
4341   safe = is_tm_safe (TREE_TYPE (old_fn));
4342   gettm_fn = builtin_decl_explicit (safe ? BUILT_IN_TM_GETTMCLONE_SAFE
4343                                     : BUILT_IN_TM_GETTMCLONE_IRR);
4344   ret = create_tmp_var (ptr_type_node, NULL);
4345   add_referenced_var (ret);
4346
4347   if (!safe)
4348     transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4349
4350   /* Discard OBJ_TYPE_REF, since we weren't able to fold it.  */
4351   if (TREE_CODE (old_fn) == OBJ_TYPE_REF)
4352     old_fn = OBJ_TYPE_REF_EXPR (old_fn);
4353
4354   g = gimple_build_call (gettm_fn, 1, old_fn);
4355   ret = make_ssa_name (ret, g);
4356   gimple_call_set_lhs (g, ret);
4357
4358   gsi_insert_before (gsi, g, GSI_SAME_STMT);
4359
4360   cgraph_create_edge (node, cgraph_get_create_node (gettm_fn), g, 0,
4361                       compute_call_stmt_bb_frequency (node->decl,
4362                                                       gimple_bb(g)));
4363
4364   /* Cast return value from tm_gettmclone* into appropriate function
4365      pointer.  */
4366   callfn = create_tmp_var (TREE_TYPE (old_fn), NULL);
4367   add_referenced_var (callfn);
4368   g2 = gimple_build_assign (callfn,
4369                             fold_build1 (NOP_EXPR, TREE_TYPE (callfn), ret));
4370   callfn = make_ssa_name (callfn, g2);
4371   gimple_assign_set_lhs (g2, callfn);
4372   gsi_insert_before (gsi, g2, GSI_SAME_STMT);
4373
4374   /* ??? This is a hack to preserve the NOTHROW bit on the call,
4375      which we would have derived from the decl.  Failure to save
4376      this bit means we might have to split the basic block.  */
4377   if (gimple_call_nothrow_p (stmt))
4378     gimple_call_set_nothrow (stmt, true);
4379
4380   gimple_call_set_fn (stmt, callfn);
4381
4382   /* Discarding OBJ_TYPE_REF above may produce incompatible LHS and RHS
4383      for a call statement.  Fix it.  */
4384   {
4385     tree lhs = gimple_call_lhs (stmt);
4386     tree rettype = TREE_TYPE (gimple_call_fntype (stmt));
4387     if (lhs
4388         && !useless_type_conversion_p (TREE_TYPE (lhs), rettype))
4389     {
4390       tree temp;
4391
4392       temp = make_rename_temp (rettype, 0);
4393       gimple_call_set_lhs (stmt, temp);
4394
4395       g2 = gimple_build_assign (lhs,
4396                                 fold_build1 (VIEW_CONVERT_EXPR,
4397                                              TREE_TYPE (lhs), temp));
4398       gsi_insert_after (gsi, g2, GSI_SAME_STMT);
4399     }
4400   }
4401
4402   update_stmt (stmt);
4403
4404   return true;
4405 }
4406
4407 /* Helper function for ipa_tm_transform_calls*.  Given a call
4408    statement in GSI which resides inside transaction REGION, redirect
4409    the call to either its wrapper function, or its clone.  */
4410
4411 static void
4412 ipa_tm_transform_calls_redirect (struct cgraph_node *node,
4413                                  struct tm_region *region,
4414                                  gimple_stmt_iterator *gsi,
4415                                  bool *need_ssa_rename_p)
4416 {
4417   gimple stmt = gsi_stmt (*gsi);
4418   struct cgraph_node *new_node;
4419   struct cgraph_edge *e = cgraph_edge (node, stmt);
4420   tree fndecl = gimple_call_fndecl (stmt);
4421
4422   /* For indirect calls, pass the address through the runtime.  */
4423   if (fndecl == NULL)
4424     {
4425       *need_ssa_rename_p |=
4426         ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
4427       return;
4428     }
4429
4430   /* Handle some TM builtins.  Ordinarily these aren't actually generated
4431      at this point, but handling these functions when written in by the
4432      user makes it easier to build unit tests.  */
4433   if (flags_from_decl_or_type (fndecl) & ECF_TM_BUILTIN)
4434     return;
4435
4436   /* Fixup recursive calls inside clones.  */
4437   /* ??? Why did cgraph_copy_node_for_versioning update the call edges
4438      for recursion but not update the call statements themselves?  */
4439   if (e->caller == e->callee && decl_is_tm_clone (current_function_decl))
4440     {
4441       gimple_call_set_fndecl (stmt, current_function_decl);
4442       return;
4443     }
4444
4445   /* If there is a replacement, use it.  */
4446   fndecl = find_tm_replacement_function (fndecl);
4447   if (fndecl)
4448     {
4449       new_node = cgraph_get_create_node (fndecl);
4450
4451       /* ??? Mark all transaction_wrap functions tm_may_enter_irr.
4452
4453          We can't do this earlier in record_tm_replacement because
4454          cgraph_remove_unreachable_nodes is called before we inject
4455          references to the node.  Further, we can't do this in some
4456          nice central place in ipa_tm_execute because we don't have
4457          the exact list of wrapper functions that would be used.
4458          Marking more wrappers than necessary results in the creation
4459          of unnecessary cgraph_nodes, which can cause some of the
4460          other IPA passes to crash.
4461
4462          We do need to mark these nodes so that we get the proper
4463          result in expand_call_tm.  */
4464       /* ??? This seems broken.  How is it that we're marking the
4465          CALLEE as may_enter_irr?  Surely we should be marking the
4466          CALLER.  Also note that find_tm_replacement_function also
4467          contains mappings into the TM runtime, e.g. memcpy.  These
4468          we know won't go irrevocable.  */
4469       new_node->local.tm_may_enter_irr = 1;
4470     }
4471   else
4472     {
4473       struct tm_ipa_cg_data *d = get_cg_data (e->callee);
4474       new_node = d->clone;
4475
4476       /* As we've already skipped pure calls and appropriate builtins,
4477          and we've already marked irrevocable blocks, if we can't come
4478          up with a static replacement, then ask the runtime.  */
4479       if (new_node == NULL)
4480         {
4481           *need_ssa_rename_p |=
4482             ipa_tm_insert_gettmclone_call (node, region, gsi, stmt);
4483           cgraph_remove_edge (e);
4484           return;
4485         }
4486
4487       fndecl = new_node->decl;
4488     }
4489
4490   cgraph_redirect_edge_callee (e, new_node);
4491   gimple_call_set_fndecl (stmt, fndecl);
4492 }
4493
4494 /* Helper function for ipa_tm_transform_calls.  For a given BB,
4495    install calls to tm_irrevocable when IRR_BLOCKS are reached,
4496    redirect other calls to the generated transactional clone.  */
4497
4498 static bool
4499 ipa_tm_transform_calls_1 (struct cgraph_node *node, struct tm_region *region,
4500                           basic_block bb, bitmap irr_blocks)
4501 {
4502   gimple_stmt_iterator gsi;
4503   bool need_ssa_rename = false;
4504
4505   if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
4506     {
4507       ipa_tm_insert_irr_call (node, region, bb);
4508       return true;
4509     }
4510
4511   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4512     {
4513       gimple stmt = gsi_stmt (gsi);
4514
4515       if (!is_gimple_call (stmt))
4516         continue;
4517       if (is_tm_pure_call (stmt))
4518         continue;
4519
4520       /* Redirect edges to the appropriate replacement or clone.  */
4521       ipa_tm_transform_calls_redirect (node, region, &gsi, &need_ssa_rename);
4522     }
4523
4524   return need_ssa_rename;
4525 }
4526
4527 /* Walk the CFG for REGION, beginning at BB.  Install calls to
4528    tm_irrevocable when IRR_BLOCKS are reached, redirect other calls to
4529    the generated transactional clone.  */
4530
4531 static bool
4532 ipa_tm_transform_calls (struct cgraph_node *node, struct tm_region *region,
4533                         basic_block bb, bitmap irr_blocks)
4534 {
4535   bool need_ssa_rename = false;
4536   edge e;
4537   edge_iterator ei;
4538   VEC(basic_block, heap) *queue = NULL;
4539   bitmap visited_blocks = BITMAP_ALLOC (NULL);
4540
4541   VEC_safe_push (basic_block, heap, queue, bb);
4542   do
4543     {
4544       bb = VEC_pop (basic_block, queue);
4545
4546       need_ssa_rename |=
4547         ipa_tm_transform_calls_1 (node, region, bb, irr_blocks);
4548
4549       if (irr_blocks && bitmap_bit_p (irr_blocks, bb->index))
4550         continue;
4551
4552       if (region && bitmap_bit_p (region->exit_blocks, bb->index))
4553         continue;
4554
4555       FOR_EACH_EDGE (e, ei, bb->succs)
4556         if (!bitmap_bit_p (visited_blocks, e->dest->index))
4557           {
4558             bitmap_set_bit (visited_blocks, e->dest->index);
4559             VEC_safe_push (basic_block, heap, queue, e->dest);
4560           }
4561     }
4562   while (!VEC_empty (basic_block, queue));
4563
4564   VEC_free (basic_block, heap, queue);
4565   BITMAP_FREE (visited_blocks);
4566
4567   return need_ssa_rename;
4568 }
4569
4570 /* Transform the calls within the TM regions within NODE.  */
4571
4572 static void
4573 ipa_tm_transform_transaction (struct cgraph_node *node)
4574 {
4575   struct tm_ipa_cg_data *d = get_cg_data (node);
4576   struct tm_region *region;
4577   bool need_ssa_rename = false;
4578
4579   current_function_decl = node->decl;
4580   push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4581   calculate_dominance_info (CDI_DOMINATORS);
4582
4583   for (region = d->all_tm_regions; region; region = region->next)
4584     {
4585       /* If we're sure to go irrevocable, don't transform anything.  */
4586       if (d->irrevocable_blocks_normal
4587           && bitmap_bit_p (d->irrevocable_blocks_normal,
4588                            region->entry_block->index))
4589         {
4590           transaction_subcode_ior (region, GTMA_DOES_GO_IRREVOCABLE);
4591           transaction_subcode_ior (region, GTMA_MAY_ENTER_IRREVOCABLE);
4592           continue;
4593         }
4594
4595       need_ssa_rename |=
4596         ipa_tm_transform_calls (node, region, region->entry_block,
4597                                 d->irrevocable_blocks_normal);
4598     }
4599
4600   if (need_ssa_rename)
4601     update_ssa (TODO_update_ssa_only_virtuals);
4602
4603   pop_cfun ();
4604   current_function_decl = NULL;
4605 }
4606
4607 /* Transform the calls within the transactional clone of NODE.  */
4608
4609 static void
4610 ipa_tm_transform_clone (struct cgraph_node *node)
4611 {
4612   struct tm_ipa_cg_data *d = get_cg_data (node);
4613   bool need_ssa_rename;
4614
4615   /* If this function makes no calls and has no irrevocable blocks,
4616      then there's nothing to do.  */
4617   /* ??? Remove non-aborting top-level transactions.  */
4618   if (!node->callees && !d->irrevocable_blocks_clone)
4619     return;
4620
4621   current_function_decl = d->clone->decl;
4622   push_cfun (DECL_STRUCT_FUNCTION (current_function_decl));
4623   calculate_dominance_info (CDI_DOMINATORS);
4624
4625   need_ssa_rename =
4626     ipa_tm_transform_calls (d->clone, NULL, single_succ (ENTRY_BLOCK_PTR),
4627                             d->irrevocable_blocks_clone);
4628
4629   if (need_ssa_rename)
4630     update_ssa (TODO_update_ssa_only_virtuals);
4631
4632   pop_cfun ();
4633   current_function_decl = NULL;
4634 }
4635
4636 /* Main entry point for the transactional memory IPA pass.  */
4637
4638 static unsigned int
4639 ipa_tm_execute (void)
4640 {
4641   cgraph_node_queue tm_callees = NULL;
4642   /* List of functions that will go irrevocable.  */
4643   cgraph_node_queue irr_worklist = NULL;
4644
4645   struct cgraph_node *node;
4646   struct tm_ipa_cg_data *d;
4647   enum availability a;
4648   unsigned int i;
4649
4650 #ifdef ENABLE_CHECKING
4651   verify_cgraph ();
4652 #endif
4653
4654   bitmap_obstack_initialize (&tm_obstack);
4655
4656   /* For all local functions marked tm_callable, queue them.  */
4657   for (node = cgraph_nodes; node; node = node->next)
4658     if (is_tm_callable (node->decl)
4659         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
4660       {
4661         d = get_cg_data (node);
4662         maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
4663       }
4664
4665   /* For all local reachable functions...  */
4666   for (node = cgraph_nodes; node; node = node->next)
4667     if (node->reachable && node->lowered
4668         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
4669       {
4670         /* ... marked tm_pure, record that fact for the runtime by
4671            indicating that the pure function is its own tm_callable.
4672            No need to do this if the function's address can't be taken.  */
4673         if (is_tm_pure (node->decl))
4674           {
4675             if (!node->local.local)
4676               record_tm_clone_pair (node->decl, node->decl);
4677             continue;
4678           }
4679
4680         current_function_decl = node->decl;
4681         push_cfun (DECL_STRUCT_FUNCTION (node->decl));
4682         calculate_dominance_info (CDI_DOMINATORS);
4683
4684         tm_region_init (NULL);
4685         if (all_tm_regions)
4686           {
4687             d = get_cg_data (node);
4688
4689             /* Scan for calls that are in each transaction.  */
4690             ipa_tm_scan_calls_transaction (d, &tm_callees);
4691
4692             /* If we saw something that will make us go irrevocable, put it
4693                in the worklist so we can scan the function later
4694                (ipa_tm_scan_irr_function) and mark the irrevocable blocks.  */
4695             if (node->local.tm_may_enter_irr)
4696               {
4697                 maybe_push_queue (node, &irr_worklist, &d->in_worklist);
4698                 d->want_irr_scan_normal = true;
4699               }
4700           }
4701
4702         pop_cfun ();
4703         current_function_decl = NULL;
4704       }
4705
4706   /* For every local function on the callee list, scan as if we will be
4707      creating a transactional clone, queueing all new functions we find
4708      along the way.  */
4709   for (i = 0; i < VEC_length (cgraph_node_p, tm_callees); ++i)
4710     {
4711       node = VEC_index (cgraph_node_p, tm_callees, i);
4712       a = cgraph_function_body_availability (node);
4713       d = get_cg_data (node);
4714
4715       /* If we saw something that will make us go irrevocable, put it
4716          in the worklist so we can scan the function later
4717          (ipa_tm_scan_irr_function) and mark the irrevocable blocks.  */
4718       if (node->local.tm_may_enter_irr)
4719         maybe_push_queue (node, &irr_worklist, &d->in_worklist);
4720
4721       /* Some callees cannot be arbitrarily cloned.  These will always be
4722          irrevocable.  Mark these now, so that we need not scan them.  */
4723       if (is_tm_irrevocable (node->decl))
4724         ipa_tm_note_irrevocable (node, &irr_worklist);
4725       else if (a <= AVAIL_NOT_AVAILABLE
4726                && !is_tm_safe_or_pure (node->decl))
4727         ipa_tm_note_irrevocable (node, &irr_worklist);
4728       else if (a >= AVAIL_OVERWRITABLE)
4729         {
4730           if (!tree_versionable_function_p (node->decl))
4731             ipa_tm_note_irrevocable (node, &irr_worklist);
4732           else if (!d->is_irrevocable)
4733             {
4734               /* If this is an alias, make sure its base is queued as well.
4735                  we need not scan the callees now, as the base will do.  */
4736               if (node->alias)
4737                 {
4738                   node = cgraph_get_node (node->thunk.alias);
4739                   d = get_cg_data (node);
4740                   maybe_push_queue (node, &tm_callees, &d->in_callee_queue);
4741                   continue;
4742                 }
4743
4744               /* Add all nodes called by this function into
4745                  tm_callees as well.  */
4746               ipa_tm_scan_calls_clone (node, &tm_callees);
4747             }
4748         }
4749     }
4750
4751   /* Iterate scans until no more work to be done.  Prefer not to use
4752      VEC_pop because the worklist tends to follow a breadth-first
4753      search of the callgraph, which should allow convergance with a
4754      minimum number of scans.  But we also don't want the worklist
4755      array to grow without bound, so we shift the array up periodically.  */
4756   for (i = 0; i < VEC_length (cgraph_node_p, irr_worklist); ++i)
4757     {
4758       if (i > 256 && i == VEC_length (cgraph_node_p, irr_worklist) / 8)
4759         {
4760           VEC_block_remove (cgraph_node_p, irr_worklist, 0, i);
4761           i = 0;
4762         }
4763
4764       node = VEC_index (cgraph_node_p, irr_worklist, i);
4765       d = get_cg_data (node);
4766       d->in_worklist = false;
4767
4768       if (d->want_irr_scan_normal)
4769         {
4770           d->want_irr_scan_normal = false;
4771           ipa_tm_scan_irr_function (node, false);
4772         }
4773       if (d->in_callee_queue && ipa_tm_scan_irr_function (node, true))
4774         ipa_tm_note_irrevocable (node, &irr_worklist);
4775     }
4776
4777   /* For every function on the callee list, collect the tm_may_enter_irr
4778      bit on the node.  */
4779   VEC_truncate (cgraph_node_p, irr_worklist, 0);
4780   for (i = 0; i < VEC_length (cgraph_node_p, tm_callees); ++i)
4781     {
4782       node = VEC_index (cgraph_node_p, tm_callees, i);
4783       if (ipa_tm_mayenterirr_function (node))
4784         {
4785           d = get_cg_data (node);
4786           gcc_assert (d->in_worklist == false);
4787           maybe_push_queue (node, &irr_worklist, &d->in_worklist);
4788         }
4789     }
4790
4791   /* Propagate the tm_may_enter_irr bit to callers until stable.  */
4792   for (i = 0; i < VEC_length (cgraph_node_p, irr_worklist); ++i)
4793     {
4794       struct cgraph_node *caller;
4795       struct cgraph_edge *e;
4796       struct ipa_ref *ref;
4797       unsigned j;
4798
4799       if (i > 256 && i == VEC_length (cgraph_node_p, irr_worklist) / 8)
4800         {
4801           VEC_block_remove (cgraph_node_p, irr_worklist, 0, i);
4802           i = 0;
4803         }
4804
4805       node = VEC_index (cgraph_node_p, irr_worklist, i);
4806       d = get_cg_data (node);
4807       d->in_worklist = false;
4808       node->local.tm_may_enter_irr = true;
4809
4810       /* Propagate back to normal callers.  */
4811       for (e = node->callers; e ; e = e->next_caller)
4812         {
4813           caller = e->caller;
4814           if (!is_tm_safe_or_pure (caller->decl)
4815               && !caller->local.tm_may_enter_irr)
4816             {
4817               d = get_cg_data (caller);
4818               maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
4819             }
4820         }
4821
4822       /* Propagate back to referring aliases as well.  */
4823       for (j = 0; ipa_ref_list_refering_iterate (&node->ref_list, j, ref); j++)
4824         {
4825           caller = ref->refering.cgraph_node;
4826           if (ref->use == IPA_REF_ALIAS
4827               && !caller->local.tm_may_enter_irr)
4828             {
4829               d = get_cg_data (caller);
4830               maybe_push_queue (caller, &irr_worklist, &d->in_worklist);
4831             }
4832         }
4833     }
4834
4835   /* Now validate all tm_safe functions, and all atomic regions in
4836      other functions.  */
4837   for (node = cgraph_nodes; node; node = node->next)
4838     if (node->reachable && node->lowered
4839         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
4840       {
4841         d = get_cg_data (node);
4842         if (is_tm_safe (node->decl))
4843           ipa_tm_diagnose_tm_safe (node);
4844         else if (d->all_tm_regions)
4845           ipa_tm_diagnose_transaction (node, d->all_tm_regions);
4846       }
4847
4848   /* Create clones.  Do those that are not irrevocable and have a
4849      positive call count.  Do those publicly visible functions that
4850      the user directed us to clone.  */
4851   for (i = 0; i < VEC_length (cgraph_node_p, tm_callees); ++i)
4852     {
4853       bool doit = false;
4854
4855       node = VEC_index (cgraph_node_p, tm_callees, i);
4856       if (node->same_body_alias)
4857         continue;
4858
4859       a = cgraph_function_body_availability (node);
4860       d = get_cg_data (node);
4861
4862       if (a <= AVAIL_NOT_AVAILABLE)
4863         doit = is_tm_callable (node->decl);
4864       else if (a <= AVAIL_AVAILABLE && is_tm_callable (node->decl))
4865         doit = true;
4866       else if (!d->is_irrevocable
4867                && d->tm_callers_normal + d->tm_callers_clone > 0)
4868         doit = true;
4869
4870       if (doit)
4871         ipa_tm_create_version (node);
4872     }
4873
4874   /* Redirect calls to the new clones, and insert irrevocable marks.  */
4875   for (i = 0; i < VEC_length (cgraph_node_p, tm_callees); ++i)
4876     {
4877       node = VEC_index (cgraph_node_p, tm_callees, i);
4878       if (node->analyzed)
4879         {
4880           d = get_cg_data (node);
4881           if (d->clone)
4882             ipa_tm_transform_clone (node);
4883         }
4884     }
4885   for (node = cgraph_nodes; node; node = node->next)
4886     if (node->reachable && node->lowered
4887         && cgraph_function_body_availability (node) >= AVAIL_OVERWRITABLE)
4888       {
4889         d = get_cg_data (node);
4890         if (d->all_tm_regions)
4891           ipa_tm_transform_transaction (node);
4892       }
4893
4894   /* Free and clear all data structures.  */
4895   VEC_free (cgraph_node_p, heap, tm_callees);
4896   VEC_free (cgraph_node_p, heap, irr_worklist);
4897   bitmap_obstack_release (&tm_obstack);
4898
4899   for (node = cgraph_nodes; node; node = node->next)
4900     node->aux = NULL;
4901
4902 #ifdef ENABLE_CHECKING
4903   verify_cgraph ();
4904 #endif
4905
4906   return 0;
4907 }
4908
4909 struct simple_ipa_opt_pass pass_ipa_tm =
4910 {
4911  {
4912   SIMPLE_IPA_PASS,
4913   "tmipa",                              /* name */
4914   gate_tm,                              /* gate */
4915   ipa_tm_execute,                       /* execute */
4916   NULL,                                 /* sub */
4917   NULL,                                 /* next */
4918   0,                                    /* static_pass_number */
4919   TV_TRANS_MEM,                         /* tv_id */
4920   PROP_ssa | PROP_cfg,                  /* properties_required */
4921   0,                                    /* properties_provided */
4922   0,                                    /* properties_destroyed */
4923   0,                                    /* todo_flags_start */
4924   TODO_dump_func,                       /* todo_flags_finish */
4925  },
4926 };
4927
4928 #include "gt-trans-mem.h"