1 @c Copyright (c) 2004 Free Software Foundation, Inc.
2 @c Free Software Foundation, Inc.
3 @c This is part of the GCC manual.
4 @c For copying conditions, see the file gcc.texi.
6 @c ---------------------------------------------------------------------
8 @c ---------------------------------------------------------------------
11 @chapter Analysis and Optimization of GIMPLE Trees
13 @cindex Optimization infrastructure for GIMPLE
15 GCC uses three main intermediate languages to represent the program
16 during compilation: GENERIC, GIMPLE and RTL@. GENERIC is a
17 language-independent representation generated by each front end. It
18 is used to serve as an interface between the parser and optimizer.
19 GENERIC is a common representation that is able to represent programs
20 written in all the languages supported by GCC@.
22 GIMPLE and RTL are used to optimize the program. GIMPLE is used for
23 target and language independent optimizations (e.g., inlining,
24 constant propagation, tail call elimination, redundancy elimination,
25 etc). Much like GENERIC, GIMPLE is a language independent, tree based
26 representation. However, it differs from GENERIC in that the GIMPLE
27 grammar is more restrictive: expressions contain no more than 3
28 operands (except function calls), it has no control flow structures
29 and expressions with side-effects are only allowed on the right hand
30 side of assignments. See the chapter describing GENERIC and GIMPLE
33 This chapter describes the data structures and functions used in the
34 GIMPLE optimizers (also known as ``tree optimizers'' or ``middle
35 end''). In particular, it focuses on all the macros, data structures,
36 functions and programming constructs needed to implement optimization
40 * GENERIC:: A high-level language-independent representation.
41 * GIMPLE:: A lower-level factored tree representation.
42 * Annotations:: Attributes for statements and variables.
43 * Statement Operands:: Variables referenced by GIMPLE statements.
44 * SSA:: Static Single Assignment representation.
45 * Alias analysis:: Representing aliased loads and stores.
52 The purpose of GENERIC is simply to provide a language-independent way of
53 representing an entire function in trees. To this end, it was necessary to
54 add a few new tree codes to the back end, but most everything was already
55 there. If you can express it with the codes in @code{gcc/tree.def}, it's
58 Early on, there was a great deal of debate about how to think about
59 statements in a tree IL. In GENERIC, a statement is defined as any
60 expression whose value, if any, is ignored. A statement will always
61 have @code{TREE_SIDE_EFFECTS} set (or it will be discarded), but a
62 non-statement expression may also have side effects. A
63 @code{CALL_EXPR}, for instance.
65 It would be possible for some local optimizations to work on the
66 GENERIC form of a function; indeed, the adapted tree inliner works
67 fine on GENERIC, but the current compiler performs inlining after
68 lowering to GIMPLE (a restricted form described in the next section).
69 Indeed, currently the frontends perform this lowering before handing
70 off to @code{tree_rest_of_compilation}, but this seems inelegant.
72 If necessary, a front end can use some language-dependent tree codes
73 in its GENERIC representation, so long as it provides a hook for
74 converting them to GIMPLE and doesn't expect them to work with any
75 (hypothetical) optimizers that run before the conversion to GIMPLE.
76 The intermediate representation used while parsing C and C++ looks
77 very little like GENERIC, but the C and C++ gimplifier hooks are
78 perfectly happy to take it as input and spit out GIMPLE.
84 GIMPLE is a simplified subset of GENERIC for use in optimization. The
85 particular subset chosen (and the name) was heavily influenced by the
86 SIMPLE IL used by the McCAT compiler project at McGill University,
87 though we have made some different choices. For one thing, SIMPLE
88 doesn't support @code{goto}; a production compiler can't afford that
91 GIMPLE retains much of the structure of the parse trees: lexical
92 scopes are represented as containers, rather than markers. However,
93 expressions are broken down into a 3-address form, using temporary
94 variables to hold intermediate values. Also, control structures are
97 In GIMPLE no container node is ever used for its value; if a
98 @code{COND_EXPR} or @code{BIND_EXPR} has a value, it is stored into a
99 temporary within the controlled blocks, and that temporary is used in
100 place of the container.
102 The compiler pass which lowers GENERIC to GIMPLE is referred to as the
103 @samp{gimplifier}. The gimplifier works recursively, replacing complex
104 statements with sequences of simple statements.
106 @c Currently, the only way to
107 @c tell whether or not an expression is in GIMPLE form is by recursively
108 @c examining it; in the future there will probably be a flag to help avoid
109 @c redundant work. FIXME FIXME
114 * GIMPLE Expressions::
117 * Rough GIMPLE Grammar::
121 @subsection Interfaces
122 @cindex gimplification
124 The tree representation of a function is stored in
125 @code{DECL_SAVED_TREE}. It is lowered to GIMPLE by a call to
126 @code{gimplify_function_tree}.
128 If a front end wants to include language-specific tree codes in the tree
129 representation which it provides to the back end, it must provide a
130 definition of @code{LANG_HOOKS_GIMPLIFY_EXPR} which knows how to
131 convert the front end trees to GIMPLE. Usually such a hook will involve
132 much of the same code for expanding front end trees to RTL. This function
133 can return fully lowered GIMPLE, or it can return GENERIC trees and let the
134 main gimplifier lower them the rest of the way; this is often simpler.
136 The C and C++ front ends currently convert directly from front end
137 trees to GIMPLE, and hand that off to the back end rather than first
138 converting to GENERIC. Their gimplifier hooks know about all the
139 @code{_STMT} nodes and how to convert them to GENERIC forms. There
140 was some work done on a genericization pass which would run first, but
141 the existence of @code{STMT_EXPR} meant that in order to convert all
142 of the C statements into GENERIC equivalents would involve walking the
143 entire tree anyway, so it was simpler to lower all the way. This
144 might change in the future if someone writes an optimization pass
145 which would work better with higher-level trees, but currently the
146 optimizers all expect GIMPLE.
148 A front end which wants to use the tree optimizers (and already has
149 some sort of whole-function tree representation) only needs to provide
150 a definition of @code{LANG_HOOKS_GIMPLIFY_EXPR}, call
151 @code{gimplify_function_tree} to lower to GIMPLE, and then hand off to
152 @code{tree_rest_of_compilation} to compile and output the function.
154 You can tell the compiler to dump a C-like representation of the GIMPLE
155 form with the flag @option{-fdump-tree-gimple}.
158 @subsection Temporaries
161 When gimplification encounters a subexpression which is too complex, it
162 creates a new temporary variable to hold the value of the subexpression,
163 and adds a new statement to initialize it before the current statement.
164 These special temporaries are known as @samp{expression temporaries}, and are
165 allocated using @code{get_formal_tmp_var}. The compiler tries to
166 always evaluate identical expressions into the same temporary, to simplify
167 elimination of redundant calculations.
169 We can only use expression temporaries when we know that it will not be
170 reevaluated before its value is used, and that it will not be otherwise
171 modified@footnote{These restrictions are derived from those in Morgan 4.8.}.
172 Other temporaries can be allocated using
173 @code{get_initialized_tmp_var} or @code{create_tmp_var}.
175 Currently, an expression like @code{a = b + 5} is not reduced any
176 further. We tried converting it to something like
181 but this bloated the representation for minimal benefit. However, a
182 variable which must live in memory cannot appear in an expression; its
183 value is explicitly loaded into a temporary first. Similarly, storing
184 the value of an expression to a memory variable goes through a
187 @node GIMPLE Expressions
188 @subsection Expressions
189 @cindex GIMPLE Expressions
191 In general, expressions in GIMPLE consist of an operation and the
192 appropriate number of simple operands; these operands must either be a
193 GIMPLE rvalue (@code{is_gimple_val}), i.e.@: a constant or a register
194 variable. More complex operands are factored out into temporaries, so
205 The same rule holds for arguments to a @code{CALL_EXPR}.
207 The target of an assignment is usually a variable, but can also be an
208 @code{INDIRECT_REF} or a compound lvalue as described below.
211 * Compound Expressions::
213 * Conditional Expressions::
214 * Logical Operators::
217 @node Compound Expressions
218 @subsubsection Compound Expressions
219 @cindex Compound Expressions
221 The left-hand side of a C comma expression is simply moved into a separate
224 @node Compound Lvalues
225 @subsubsection Compound Lvalues
226 @cindex Compound Lvalues
228 Currently compound lvalues involving array and structure field references
229 are not broken down; an expression like @code{a.b[2] = 42} is not reduced
230 any further (though complex array subscripts are). This restriction is a
231 workaround for limitations in later optimizers; if we were to convert this
239 alias analysis would not remember that the reference to @code{T1[2]} came
240 by way of @code{a.b}, so it would think that the assignment could alias
241 another member of @code{a}; this broke @code{struct-alias-1.c}. Future
242 optimizer improvements may make this limitation unnecessary.
244 @node Conditional Expressions
245 @subsubsection Conditional Expressions
246 @cindex Conditional Expressions
248 A C @code{?:} expression is converted into an @code{if} statement with
249 each branch assigning to the same temporary. So,
263 Tree level if-conversion pass re-introduces @code{?:} expression, if appropriate.
264 It is used to vectorize loops with conditions using vector conditional operations.
266 Note that in GIMPLE, @code{if} statements are also represented using
267 @code{COND_EXPR}, as described below.
269 @node Logical Operators
270 @subsubsection Logical Operators
271 @cindex Logical Operators
273 Except when they appear in the condition operand of a @code{COND_EXPR},
274 logical `and' and `or' operators are simplified as follows:
275 @code{a = b && c} becomes
284 Note that @code{T1} in this example cannot be an expression temporary,
285 because it has two different assignments.
288 @subsection Statements
291 Most statements will be assignment statements, represented by
292 @code{MODIFY_EXPR}. A @code{CALL_EXPR} whose value is ignored can
293 also be a statement. No other C expressions can appear at statement level;
294 a reference to a volatile object is converted into a @code{MODIFY_EXPR}.
295 In GIMPLE form, type of @code{MODIFY_EXPR} is not meaningful. Instead, use type
298 There are also several varieties of complex statements.
302 * Statement Sequences::
305 * Selection Statements::
308 * GIMPLE Exception Handling::
312 @subsubsection Blocks
315 Block scopes and the variables they declare in GENERIC and GIMPLE are
316 expressed using the @code{BIND_EXPR} code, which in previous versions of
317 GCC was primarily used for the C statement-expression extension.
319 Variables in a block are collected into @code{BIND_EXPR_VARS} in
320 declaration order. Any runtime initialization is moved out of
321 @code{DECL_INITIAL} and into a statement in the controlled block. When
322 gimplifying from C or C++, this initialization replaces the
325 Variable-length arrays (VLAs) complicate this process, as their size often
326 refers to variables initialized earlier in the block. To handle this, we
327 currently split the block at that point, and move the VLA into a new, inner
328 @code{BIND_EXPR}. This strategy may change in the future.
330 @code{DECL_SAVED_TREE} for a GIMPLE function will always be a
331 @code{BIND_EXPR} which contains declarations for the temporary variables
332 used in the function.
334 A C++ program will usually contain more @code{BIND_EXPR}s than there are
335 syntactic blocks in the source code, since several C++ constructs have
336 implicit scopes associated with them. On the other hand, although the C++
337 front end uses pseudo-scopes to handle cleanups for objects with
338 destructors, these don't translate into the GIMPLE form; multiple
339 declarations at the same level use the same BIND_EXPR.
341 @node Statement Sequences
342 @subsubsection Statement Sequences
343 @cindex Statement Sequences
345 Multiple statements at the same nesting level are collected into a
346 @code{STATEMENT_LIST}. Statement lists are modified and traversed
347 using the interface in @samp{tree-iterator.h}.
349 @node Empty Statements
350 @subsubsection Empty Statements
351 @cindex Empty Statements
353 Whenever possible, statements with no effect are discarded. But if they
354 are nested within another construct which cannot be discarded for some
355 reason, they are instead replaced with an empty statement, generated by
356 @code{build_empty_stmt}. Initially, all empty statements were shared,
357 after the pattern of the Java front end, but this caused a lot of trouble in
360 An empty statement is represented as @code{(void)0}.
366 At one time loops were expressed in GIMPLE using @code{LOOP_EXPR}, but
367 now they are lowered to explicit gotos.
369 @node Selection Statements
370 @subsubsection Selection Statements
371 @cindex Selection Statements
373 A simple selection statement, such as the C @code{if} statement, is
374 expressed in GIMPLE using a void @code{COND_EXPR}. If only one branch is
375 used, the other is filled with an empty statement.
377 Normally, the condition expression is reduced to a simple comparison. If
378 it is a shortcut (@code{&&} or @code{||}) expression, however, we try to
379 break up the @code{if} into multiple @code{if}s so that the implied shortcut
380 is taken directly, much like the transformation done by @code{do_jump} in
383 A @code{SWITCH_EXPR} in GIMPLE contains the condition and a
384 @code{TREE_VEC} of @code{CASE_LABEL_EXPR}s describing the case values
385 and corresponding @code{LABEL_DECL}s to jump to. The body of the
386 @code{switch} is moved after the @code{SWITCH_EXPR}.
392 Other jumps are expressed by either @code{GOTO_EXPR} or @code{RETURN_EXPR}.
394 The operand of a @code{GOTO_EXPR} must be either a label or a variable
395 containing the address to jump to.
397 The operand of a @code{RETURN_EXPR} is either @code{NULL_TREE} or a
398 @code{MODIFY_EXPR} which sets the return value. It would be nice to
399 move the @code{MODIFY_EXPR} into a separate statement, but the special
400 return semantics in @code{expand_return} make that difficult. It may
401 still happen in the future, perhaps by moving most of that logic into
402 @code{expand_assignment}.
405 @subsubsection Cleanups
408 Destructors for local C++ objects and similar dynamic cleanups are
409 represented in GIMPLE by a @code{TRY_FINALLY_EXPR}. When the controlled
410 block exits, the cleanup is run.
412 @code{TRY_FINALLY_EXPR} complicates the flow graph, since the cleanup
413 needs to appear on every edge out of the controlled block; this
414 reduces the freedom to move code across these edges. Therefore, the
415 EH lowering pass which runs before most of the optimization passes
416 eliminates these expressions by explicitly adding the cleanup to each
419 @node GIMPLE Exception Handling
420 @subsubsection Exception Handling
421 @cindex GIMPLE Exception Handling
423 Other exception handling constructs are represented using
424 @code{TRY_CATCH_EXPR}. The handler operand of a @code{TRY_CATCH_EXPR}
425 can be a normal statement to be executed if the controlled block throws an
426 exception, or it can have one of two special forms:
429 @item A @code{CATCH_EXPR} executes its handler if the thrown exception
430 matches one of the allowed types. Multiple handlers can be
431 expressed by a sequence of @code{CATCH_EXPR} statements.
432 @item An @code{EH_FILTER_EXPR} executes its handler if the thrown
433 exception does not match one of the allowed types.
436 Currently throwing an exception is not directly represented in GIMPLE,
437 since it is implemented by calling a function. At some point in the future
438 we will want to add some way to express that the call will throw an
439 exception of a known type.
441 Just before running the optimizers, the compiler lowers the high-level
442 EH constructs above into a set of @samp{goto}s, magic labels, and EH
443 regions. Continuing to unwind at the end of a cleanup is represented
444 with a @code{RESX_EXPR}.
447 @subsection GIMPLE Example
448 @cindex GIMPLE Example
451 struct A @{ A(); ~A(); @};
458 int j = (--i, i ? 0 : 1);
460 for (int x = 42; x > 0; --x)
527 @node Rough GIMPLE Grammar
528 @subsection Rough GIMPLE Grammar
529 @cindex Rough GIMPLE Grammar
534 DECL_SAVED_TREE -> block
537 BIND_EXPR_VARS -> DECL chain
538 BIND_EXPR_BLOCK -> BLOCK
543 op0 -> non-compound-stmt
565 op2 -> TREE_VEC of CASE_LABEL_EXPRs
568 op0 -> LABEL_DECL | '*' ID
596 op0 -> _DECL | '&' _DECL
604 varname : compref | _DECL
605 lhs: varname | '*' _DECL
606 pseudo-lval: _DECL | '*' _DECL
609 op0 -> compref | pseudo-lval
611 op0 -> compref | pseudo-lval
614 condition : val | val relop val
625 unop: '+' | '-' | '!' | '~'
627 binop: relop | '-' | '+' | '/' | '*'
628 | '%' | '&' | '|' | '<<' | '>>' | '^'
630 relop: All tree codes of class '<'
637 The optimizers need to associate attributes with statements and
638 variables during the optimization process. For instance, we need to
639 know what basic block does a statement belong to or whether a variable
640 has aliases. All these attributes are stored in data structures
641 called annotations which are then linked to the field @code{ann} in
642 @code{struct tree_common}.
644 Presently, we define annotations for statements (@code{stmt_ann_t}),
645 variables (@code{var_ann_t}) and SSA names (@code{ssa_name_ann_t}).
646 Annotations are defined and documented in @file{tree-flow.h}.
649 @node Statement Operands
650 @section Statement Operands
652 @cindex virtual operands
653 @cindex real operands
654 @findex get_stmt_operands
657 Almost every GIMPLE statement will contain a reference to a variable
658 or memory location. Since statements come in different shapes and
659 sizes, their operands are going to be located at various spots inside
660 the statement's tree. To facilitate access to the statement's
661 operands, they are organized into arrays associated inside each
662 statement's annotation. Each element in an operand array is a pointer
663 to a @code{VAR_DECL}, @code{PARM_DECL} or @code{SSA_NAME} tree node.
664 This provides a very convenient way of examining and replacing
667 Data flow analysis and optimization is done on all tree nodes
668 representing variables. Any node for which @code{SSA_VAR_P} returns
669 nonzero is considered when scanning statement operands. However, not
670 all @code{SSA_VAR_P} variables are processed in the same way. For the
671 purposes of optimization, we need to distinguish between references to
672 local scalar variables and references to globals, statics, structures,
673 arrays, aliased variables, etc. The reason is simple, the compiler
674 can gather complete data flow information for a local scalar. On the
675 other hand, a global variable may be modified by a function call, it
676 may not be possible to keep track of all the elements of an array or
677 the fields of a structure, etc.
679 The operand scanner gathers two kinds of operands: @dfn{real} and
680 @dfn{virtual}. An operand for which @code{is_gimple_reg} returns true
681 is considered real, otherwise it is a virtual operand. We also
682 distinguish between uses and definitions. An operand is used if its
683 value is loaded by the statement (e.g., the operand at the RHS of an
684 assignment). If the statement assigns a new value to the operand, the
685 operand is considered a definition (e.g., the operand at the LHS of
688 Virtual and real operands also have very different data flow
689 properties. Real operands are unambiguous references to the
690 full object that they represent. For instance, given
699 Since @code{a} and @code{b} are non-aliased locals, the statement
700 @code{a = b} will have one real definition and one real use because
701 variable @code{b} is completely modified with the contents of
702 variable @code{a}. Real definition are also known as @dfn{killing
703 definitions}. Similarly, the use of @code{a} reads all its bits.
705 In contrast, virtual operands are used with variables that can have
706 a partial or ambiguous reference. This includes structures, arrays,
707 globals, and aliased variables. In these cases, we have two types of
708 definitions. For globals, structures, and arrays, we can determine from
709 a statement whether a variable of these types has a killing definition.
710 If the variable does, then the statement is marked as having a
711 @dfn{must definition} of that variable. However, if a statement is only
712 defining a part of the variable (i.e.@: a field in a structure), or if we
713 know that a statement might define the variable but we cannot say for sure,
714 then we mark that statement as having a @dfn{may definition}. For
730 The assignment @code{*p = 5} may be a definition of @code{a} or
731 @code{b}. If we cannot determine statically where @code{p} is
732 pointing to at the time of the store operation, we create virtual
733 definitions to mark that statement as a potential definition site for
734 @code{a} and @code{b}. Memory loads are similarly marked with virtual
735 use operands. Virtual operands are shown in tree dumps right before
736 the statement that contains them. To request a tree dump with virtual
737 operands, use the @option{-vops} option to @option{-fdump-tree}:
757 Notice that @code{V_MAY_DEF} operands have two copies of the referenced
758 variable. This indicates that this is not a killing definition of
759 that variable. In this case we refer to it as a @dfn{may definition}
760 or @dfn{aliased store}. The presence of the second copy of the
761 variable in the @code{V_MAY_DEF} operand will become important when the
762 function is converted into SSA form. This will be used to link all
763 the non-killing definitions to prevent optimizations from making
764 incorrect assumptions about them.
766 Operands are collected by @file{tree-ssa-operands.c}. They are stored
767 inside each statement's annotation and can be accessed with
768 @code{DEF_OPS}, @code{USE_OPS}, @code{V_MAY_DEF_OPS},
769 @code{V_MUST_DEF_OPS} and @code{VUSE_OPS}. The following are all the
770 accessor macros available to access USE operands. To access all the
771 other operand arrays, just change the name accordingly:
773 @defmac USE_OPS (@var{ann})
774 Returns the array of operands used by the statement with annotation
778 @defmac STMT_USE_OPS (@var{stmt})
779 Alternate version of USE_OPS that takes the statement @var{stmt} as
783 @defmac NUM_USES (@var{ops})
784 Return the number of USE operands in array @var{ops}.
787 @defmac USE_OP_PTR (@var{ops}, @var{i})
788 Return a pointer to the @var{i}th operand in array @var{ops}.
791 @defmac USE_OP (@var{ops}, @var{i})
792 Return the @var{i}th operand in array @var{ops}.
795 The following function shows how to print all the operands of a given
800 print_ops (tree stmt)
803 v_may_def_optype v_may_defs;
804 v_must_def_optype v_must_defs;
810 get_stmt_operands (stmt);
811 ann = stmt_ann (stmt);
813 defs = DEF_OPS (ann);
814 for (i = 0; i < NUM_DEFS (defs); i++)
815 print_generic_expr (stderr, DEF_OP (defs, i), 0);
817 uses = USE_OPS (ann);
818 for (i = 0; i < NUM_USES (uses); i++)
819 print_generic_expr (stderr, USE_OP (uses, i), 0);
821 v_may_defs = V_MAY_DEF_OPS (ann);
822 for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
824 print_generic_expr (stderr, V_MAY_DEF_OP (v_may_defs, i), 0);
825 print_generic_expr (stderr, V_MAY_DEF_RESULT (v_may_defs, i), 0);
828 v_must_defs = V_MUST_DEF_OPS (ann);
829 for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
830 print_generic_expr (stderr, V_MUST_DEF_OP (v_must_defs, i), 0);
832 vuses = VUSE_OPS (ann);
833 for (i = 0; i < NUM_VUSES (vuses); i++)
834 print_generic_expr (stderr, VUSE_OP (vuses, i), 0);
838 To collect the operands, you first need to call
839 @code{get_stmt_operands}. Since that is a potentially expensive
840 operation, statements are only scanned if they have been marked
841 modified by a call to @code{modify_stmt}. So, if your pass replaces
842 operands in a statement, make sure to call @code{modify_stmt}.
844 @subsection Operand Iterators
845 @cindex Operand Iterators
847 There is an alternative to iterating over the operands in a statement.
848 It is especially useful when you wish to perform the same operation on
849 more than one type of operand. The previous example could be
850 rewritten as follows:
854 print_ops (tree stmt)
859 get_stmt_operands (stmt);
860 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_OPERANDS)
861 print_generic_expr (stderr, var, 0);
867 @item Determine whether you are need to see the operand pointers, or just the
868 trees, and choose the appropriate macro:
873 use_operand_p FOR_EACH_SSA_USE_OPERAND
874 def_operand_p FOR_EACH_SSA_DEF_OPERAND
875 tree FOR_EACH_SSA_TREE_OPERAND
878 @item You need to declare a variable of the type you are interested
879 in, and an ssa_op_iter structure which serves as the loop
880 controlling variable.
882 @item Determine which operands you wish to use, and specify the flags of
883 those you are interested in. They are documented in
884 @file{tree-ssa-operands.h}:
887 #define SSA_OP_USE 0x01 /* Real USE operands. */
888 #define SSA_OP_DEF 0x02 /* Real DEF operands. */
889 #define SSA_OP_VUSE 0x04 /* VUSE operands. */
890 #define SSA_OP_VMAYUSE 0x08 /* USE portion of V_MAY_DEFS. */
891 #define SSA_OP_VMAYDEF 0x10 /* DEF portion of V_MAY_DEFS. */
892 #define SSA_OP_VMUSTDEF 0x20 /* V_MUST_DEF definitions. */
894 /* These are commonly grouped operand flags. */
895 #define SSA_OP_VIRTUAL_USES (SSA_OP_VUSE | SSA_OP_VMAYUSE)
896 #define SSA_OP_VIRTUAL_DEFS (SSA_OP_VMAYDEF | SSA_OP_VMUSTDEF)
897 #define SSA_OP_ALL_USES (SSA_OP_VIRTUAL_USES | SSA_OP_USE)
898 #define SSA_OP_ALL_DEFS (SSA_OP_VIRTUAL_DEFS | SSA_OP_DEF)
899 #define SSA_OP_ALL_OPERANDS (SSA_OP_ALL_USES | SSA_OP_ALL_DEFS)
903 So if you want to look at the use pointers for all the @code{USE} and
904 @code{VUSE} operands, you would do something like:
910 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, (SSA_OP_USE | SSA_OP_VUSE))
912 process_use_ptr (use_p);
916 The @code{_TREE_} macro is basically the same as the @code{USE} and
917 @code{DEF} macros, only with the use or def dereferenced via
918 @code{USE_FROM_PTR (use_p)} and @code{DEF_FROM_PTR (def_p)}. Since we
919 aren't using operand pointers, use and defs flags can be mixed.
925 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_VUSE | SSA_OP_VMUSTDEF)
927 print_generic_expr (stderr, var, TDF_SLIM);
931 Note that @code{V_MAY_DEFS} are broken into 2 flags, one for the
932 @code{DEF} portion (@code{SSA_OP_VMAYDEF}) and one for the USE portion
933 (@code{SSA_OP_VMAYUSE}). If all you want to look at are the
934 @code{V_MAY_DEFS} together, there is a fourth iterator macro for this,
935 which returns both a def_operand_p and a use_operand_p for each
936 @code{V_MAY_DEF} in the statement. Note that you don't need any flags for
944 FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
951 There are many examples in the code as well, as well as the
952 documentation in @file{tree-ssa-operands.h}.
956 @section Static Single Assignment
958 @cindex static single assignment
960 Most of the tree optimizers rely on the data flow information provided
961 by the Static Single Assignment (SSA) form. We implement the SSA form
962 as described in @cite{R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and
963 K. Zadeck. Efficiently Computing Static Single Assignment Form and the
964 Control Dependence Graph. ACM Transactions on Programming Languages
965 and Systems, 13(4):451-490, October 1991}.
967 The SSA form is based on the premise that program variables are
968 assigned in exactly one location in the program. Multiple assignments
969 to the same variable create new versions of that variable. Naturally,
970 actual programs are seldom in SSA form initially because variables
971 tend to be assigned multiple times. The compiler modifies the program
972 representation so that every time a variable is assigned in the code,
973 a new version of the variable is created. Different versions of the
974 same variable are distinguished by subscripting the variable name with
975 its version number. Variables used in the right-hand side of
976 expressions are renamed so that their version number matches that of
977 the most recent assignment.
979 We represent variable versions using @code{SSA_NAME} nodes. The
980 renaming process in @file{tree-ssa.c} wraps every real and
981 virtual operand with an @code{SSA_NAME} node which contains
982 the version number and the statement that created the
983 @code{SSA_NAME}. Only definitions and virtual definitions may
984 create new @code{SSA_NAME} nodes.
986 Sometimes, flow of control makes it impossible to determine what is the
987 most recent version of a variable. In these cases, the compiler
988 inserts an artificial definition for that variable called
989 @dfn{PHI function} or @dfn{PHI node}. This new definition merges
990 all the incoming versions of the variable to create a new name
991 for it. For instance,
1001 # a_4 = PHI <a_1, a_2, a_3>
1005 Since it is not possible to determine which of the three branches
1006 will be taken at runtime, we don't know which of @code{a_1},
1007 @code{a_2} or @code{a_3} to use at the return statement. So, the
1008 SSA renamer creates a new version @code{a_4} which is assigned
1009 the result of ``merging'' @code{a_1}, @code{a_2} and @code{a_3}.
1010 Hence, PHI nodes mean ``one of these operands. I don't know
1013 The following macros can be used to examine PHI nodes
1015 @defmac PHI_RESULT (@var{phi})
1016 Returns the @code{SSA_NAME} created by PHI node @var{phi} (i.e.,
1020 @defmac PHI_NUM_ARGS (@var{phi})
1021 Returns the number of arguments in @var{phi}. This number is exactly
1022 the number of incoming edges to the basic block holding @var{phi}@.
1025 @defmac PHI_ARG_ELT (@var{phi}, @var{i})
1026 Returns a tuple representing the @var{i}th argument of @var{phi}@.
1027 Each element of this tuple contains an @code{SSA_NAME} @var{var} and
1028 the incoming edge through which @var{var} flows.
1031 @defmac PHI_ARG_EDGE (@var{phi}, @var{i})
1032 Returns the incoming edge for the @var{i}th argument of @var{phi}.
1035 @defmac PHI_ARG_DEF (@var{phi}, @var{i})
1036 Returns the @code{SSA_NAME} for the @var{i}th argument of @var{phi}.
1040 @subsection Preserving the SSA form
1041 @findex vars_to_rename
1042 @cindex preserving SSA form
1043 Some optimization passes make changes to the function that
1044 invalidate the SSA property. This can happen when a pass has
1045 added new variables or changed the program so that variables that
1046 were previously aliased aren't anymore.
1048 Whenever something like this happens, the affected variables must
1049 be renamed into SSA form again. To do this, you should mark the
1050 new variables in the global bitmap @code{vars_to_rename}. Once
1051 your pass has finished, the pass manager will invoke the SSA
1052 renamer to put the program into SSA once more.
1054 @subsection Examining @code{SSA_NAME} nodes
1055 @cindex examining SSA_NAMEs
1057 The following macros can be used to examine @code{SSA_NAME} nodes
1059 @defmac SSA_NAME_DEF_STMT (@var{var})
1060 Returns the statement @var{s} that creates the @code{SSA_NAME}
1061 @var{var}. If @var{s} is an empty statement (i.e., @code{IS_EMPTY_STMT
1062 (@var{s})} returns @code{true}), it means that the first reference to
1063 this variable is a USE or a VUSE@.
1066 @defmac SSA_NAME_VERSION (@var{var})
1067 Returns the version number of the @code{SSA_NAME} object @var{var}.
1071 @subsection Walking use-def chains
1073 @deftypefn {Tree SSA function} void walk_use_def_chains (@var{var}, @var{fn}, @var{data})
1075 Walks use-def chains starting at the @code{SSA_NAME} node @var{var}.
1076 Calls function @var{fn} at each reaching definition found. Function
1077 @var{FN} takes three arguments: @var{var}, its defining statement
1078 (@var{def_stmt}) and a generic pointer to whatever state information
1079 that @var{fn} may want to maintain (@var{data}). Function @var{fn} is
1080 able to stop the walk by returning @code{true}, otherwise in order to
1081 continue the walk, @var{fn} should return @code{false}.
1083 Note, that if @var{def_stmt} is a @code{PHI} node, the semantics are
1084 slightly different. For each argument @var{arg} of the PHI node, this
1088 @item Walk the use-def chains for @var{arg}.
1089 @item Call @code{FN (@var{arg}, @var{phi}, @var{data})}.
1092 Note how the first argument to @var{fn} is no longer the original
1093 variable @var{var}, but the PHI argument currently being examined.
1094 If @var{fn} wants to get at @var{var}, it should call
1095 @code{PHI_RESULT} (@var{phi}).
1098 @subsection Walking the dominator tree
1100 @deftypefn {Tree SSA function} void walk_dominator_tree (@var{walk_data}, @var{bb})
1102 This function walks the dominator tree for the current CFG calling a
1103 set of callback functions defined in @var{struct dom_walk_data} in
1104 @file{domwalk.h}. The call back functions you need to define give you
1105 hooks to execute custom code at various points during traversal:
1108 @item Once to initialize any local data needed while processing
1109 @var{bb} and its children. This local data is pushed into an
1110 internal stack which is automatically pushed and popped as the
1111 walker traverses the dominator tree.
1113 @item Once before traversing all the statements in the @var{bb}.
1115 @item Once for every statement inside @var{bb}.
1117 @item Once after traversing all the statements and before recursing
1118 into @var{bb}'s dominator children.
1120 @item It then recurses into all the dominator children of @var{bb}.
1122 @item After recursing into all the dominator children of @var{bb} it
1123 can, optionally, traverse every statement in @var{bb} again
1124 (i.e., repeating steps 2 and 3).
1126 @item Once after walking the statements in @var{bb} and @var{bb}'s
1127 dominator children. At this stage, the block local data stack
1132 @node Alias analysis
1133 @section Alias analysis
1135 @cindex flow-sensitive alias analysis
1136 @cindex flow-insensitive alias analysis
1138 Alias analysis proceeds in 3 main phases:
1141 @item Points-to and escape analysis.
1143 This phase walks the use-def chains in the SSA web looking for
1147 @item Assignments of the form @code{P_i = &VAR}
1148 @item Assignments of the form P_i = malloc()
1149 @item Pointers and ADDR_EXPR that escape the current function.
1152 The concept of `escaping' is the same one used in the Java world.
1153 When a pointer or an ADDR_EXPR escapes, it means that it has been
1154 exposed outside of the current function. So, assignment to
1155 global variables, function arguments and returning a pointer are
1158 This is where we are currently limited. Since not everything is
1159 renamed into SSA, we lose track of escape properties when a
1160 pointer is stashed inside a field in a structure, for instance.
1161 In those cases, we are assuming that the pointer does escape.
1163 We use escape analysis to determine whether a variable is
1164 call-clobbered. Simply put, if an ADDR_EXPR escapes, then the
1165 variable is call-clobbered. If a pointer P_i escapes, then all
1166 the variables pointed-to by P_i (and its memory tag) also escape.
1168 @item Compute flow-sensitive aliases
1170 We have two classes of memory tags. Memory tags associated with
1171 the pointed-to data type of the pointers in the program. These
1172 tags are called ``type memory tag'' (TMT). The other class are
1173 those associated with SSA_NAMEs, called ``name memory tag'' (NMT).
1174 The basic idea is that when adding operands for an INDIRECT_REF
1175 *P_i, we will first check whether P_i has a name tag, if it does
1176 we use it, because that will have more precise aliasing
1177 information. Otherwise, we use the standard type tag.
1179 In this phase, we go through all the pointers we found in
1180 points-to analysis and create alias sets for the name memory tags
1181 associated with each pointer P_i. If P_i escapes, we mark
1182 call-clobbered the variables it points to and its tag.
1185 @item Compute flow-insensitive aliases
1187 This pass will compare the alias set of every type memory tag and
1188 every addressable variable found in the program. Given a type
1189 memory tag TMT and an addressable variable V@. If the alias sets
1190 of TMT and V conflict (as computed by may_alias_p), then V is
1191 marked as an alias tag and added to the alias set of TMT@.
1194 For instance, consider the following function:
1213 After aliasing analysis has finished, the type memory tag for
1214 pointer @code{p} will have two aliases, namely variables @code{a} and
1216 Every time pointer @code{p} is dereferenced, we want to mark the
1217 operation as a potential reference to @code{a} and @code{b}.
1228 # p_1 = PHI <p_4(1), p_6(2)>;
1230 # a_7 = V_MAY_DEF <a_3>;
1231 # b_8 = V_MAY_DEF <b_5>;
1234 # a_9 = V_MAY_DEF <a_7>
1244 In certain cases, the list of may aliases for a pointer may grow
1245 too large. This may cause an explosion in the number of virtual
1246 operands inserted in the code. Resulting in increased memory
1247 consumption and compilation time.
1249 When the number of virtual operands needed to represent aliased
1250 loads and stores grows too large (configurable with @option{--param
1251 max-aliased-vops}), alias sets are grouped to avoid severe
1252 compile-time slow downs and memory consumption. The alias
1253 grouping heuristic proceeds as follows:
1256 @item Sort the list of pointers in decreasing number of contributed
1259 @item Take the first pointer from the list and reverse the role
1260 of the memory tag and its aliases. Usually, whenever an
1261 aliased variable Vi is found to alias with a memory tag
1262 T, we add Vi to the may-aliases set for T@. Meaning that
1263 after alias analysis, we will have:
1266 may-aliases(T) = @{ V1, V2, V3, ..., Vn @}
1269 This means that every statement that references T, will get
1270 @code{n} virtual operands for each of the Vi tags. But, when
1271 alias grouping is enabled, we make T an alias tag and add it
1272 to the alias set of all the Vi variables:
1275 may-aliases(V1) = @{ T @}
1276 may-aliases(V2) = @{ T @}
1278 may-aliases(Vn) = @{ T @}
1281 This has two effects: (a) statements referencing T will only get
1282 a single virtual operand, and, (b) all the variables Vi will now
1283 appear to alias each other. So, we lose alias precision to
1284 improve compile time. But, in theory, a program with such a high
1285 level of aliasing should not be very optimizable in the first
1288 @item Since variables may be in the alias set of more than one
1289 memory tag, the grouping done in step (2) needs to be extended
1290 to all the memory tags that have a non-empty intersection with
1291 the may-aliases set of tag T@. For instance, if we originally
1292 had these may-aliases sets:
1295 may-aliases(T) = @{ V1, V2, V3 @}
1296 may-aliases(R) = @{ V2, V4 @}
1299 In step (2) we would have reverted the aliases for T as:
1302 may-aliases(V1) = @{ T @}
1303 may-aliases(V2) = @{ T @}
1304 may-aliases(V3) = @{ T @}
1307 But note that now V2 is no longer aliased with R@. We could
1308 add R to may-aliases(V2), but we are in the process of
1309 grouping aliases to reduce virtual operands so what we do is
1310 add V4 to the grouping to obtain:
1313 may-aliases(V1) = @{ T @}
1314 may-aliases(V2) = @{ T @}
1315 may-aliases(V3) = @{ T @}
1316 may-aliases(V4) = @{ T @}
1319 @item If the total number of virtual operands due to aliasing is
1320 still above the threshold set by max-alias-vops, go back to (2).