2 If Passes.html is up to date, the following "one-liner" should print
5 egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \
6 -e '^ <a name=".*">.*</a>$' < Passes.html >html; \
7 perl >help <<'EOT' && diff -u help html; rm -f help html
8 open HTML, "<Passes.html" or die "open: Passes.html: $!\n";
10 m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next;
11 $order{$1} = sprintf("%03d", 1 + int %order);
13 open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n";
15 m:^ -([^ ]+) +- (.*)$: or next;
17 $o = "000" unless defined $o;
18 push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n";
19 push @y, "$o <a name=\"$1\">-$1: $2</a>\n";
21 @x = map { s/^\d\d\d//; $_ } sort @x;
22 @y = map { s/^\d\d\d//; $_ } sort @y;
26 This (real) one-liner can also be helpful when converting comments to HTML:
28 perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print " <p>\n" if !$on && $_ =~ /\S/; print " </p>\n" if $on && $_ =~ /^\s*$/; print " $_\n"; $on = ($_ =~ /\S/); } print " </p>\n" if $on'
30 ====================================
31 LLVM's Analysis and Transform Passes
32 ====================================
40 This document serves as a high level summary of the optimization features that
41 LLVM provides. Optimizations are implemented as Passes that traverse some
42 portion of a program to either collect information or transform the program.
43 The table below divides the passes that LLVM provides into three categories.
44 Analysis passes compute information that other passes can use or for debugging
45 or program visualization purposes. Transform passes can use (or invalidate)
46 the analysis passes. Transform passes all mutate the program in some way.
47 Utility passes provides some utility but don't otherwise fit categorization.
48 For example passes to extract functions to bitcode or write a module to bitcode
49 are neither analysis nor transform passes. The table of contents above
50 provides a quick summary of each pass and links to the more complete pass
51 description later in the document.
56 This section describes the LLVM Analysis Passes.
58 ``-aa-eval``: Exhaustive Alias Analysis Precision Evaluator
59 -----------------------------------------------------------
61 This is a simple N^2 alias analysis accuracy evaluator. Basically, for each
62 function in the program, it simply queries to see how the alias analysis
63 implementation answers alias queries between each pair of pointers in the
66 This is inspired and adapted from code by: Naveen Neelakantam, Francesco
67 Spadini, and Wojciech Stryjewski.
69 ``-basicaa``: Basic Alias Analysis (stateless AA impl)
70 ------------------------------------------------------
72 A basic alias analysis pass that implements identities (two different globals
73 cannot alias, etc), but does no stateful analysis.
75 ``-basiccg``: Basic CallGraph Construction
76 ------------------------------------------
80 ``-count-aa``: Count Alias Analysis Query Responses
81 ---------------------------------------------------
83 A pass which can be used to count how many alias queries are being made and how
84 the alias analysis implementation being used responds.
88 ``-da``: Dependence Analysis
89 ----------------------------
91 Dependence analysis framework, which is used to detect dependences in memory
94 ``-debug-aa``: AA use debugger
95 ------------------------------
97 This simple pass checks alias analysis users to ensure that if they create a
98 new value, they do not query AA without informing it of the value. It acts as
99 a shim over any other AA pass you want.
101 Yes keeping track of every value in the program is expensive, but this is a
104 ``-domfrontier``: Dominance Frontier Construction
105 -------------------------------------------------
107 This pass is a simple dominator construction algorithm for finding forward
110 ``-domtree``: Dominator Tree Construction
111 -----------------------------------------
113 This pass is a simple dominator construction algorithm for finding forward
117 ``-dot-callgraph``: Print Call Graph to "dot" file
118 --------------------------------------------------
120 This pass, only available in ``opt``, prints the call graph into a ``.dot``
121 graph. This graph can then be processed with the "dot" tool to convert it to
122 postscript or some other suitable format.
124 ``-dot-cfg``: Print CFG of function to "dot" file
125 -------------------------------------------------
127 This pass, only available in ``opt``, prints the control flow graph into a
128 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
129 to convert it to postscript or some other suitable format.
131 ``-dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)
132 --------------------------------------------------------------------------------
134 This pass, only available in ``opt``, prints the control flow graph into a
135 ``.dot`` graph, omitting the function bodies. This graph can then be processed
136 with the :program:`dot` tool to convert it to postscript or some other suitable
139 ``-dot-dom``: Print dominance tree of function to "dot" file
140 ------------------------------------------------------------
142 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
143 graph. This graph can then be processed with the :program:`dot` tool to
144 convert it to postscript or some other suitable format.
146 ``-dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)
147 -------------------------------------------------------------------------------------------
149 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
150 graph, omitting the function bodies. This graph can then be processed with the
151 :program:`dot` tool to convert it to postscript or some other suitable format.
153 ``-dot-postdom``: Print postdominance tree of function to "dot" file
154 --------------------------------------------------------------------
156 This pass, only available in ``opt``, prints the post dominator tree into a
157 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
158 to convert it to postscript or some other suitable format.
160 ``-dot-postdom-only``: Print postdominance tree of function to "dot" file (with no function bodies)
161 ---------------------------------------------------------------------------------------------------
163 This pass, only available in ``opt``, prints the post dominator tree into a
164 ``.dot`` graph, omitting the function bodies. This graph can then be processed
165 with the :program:`dot` tool to convert it to postscript or some other suitable
168 ``-globalsmodref-aa``: Simple mod/ref analysis for globals
169 ----------------------------------------------------------
171 This simple pass provides alias and mod/ref information for global values that
172 do not have their address taken, and keeps track of whether functions read or
173 write memory (are "pure"). For this simple (but very common) case, we can
174 provide pretty accurate and useful information.
176 ``-instcount``: Counts the various types of ``Instruction``\ s
177 --------------------------------------------------------------
179 This pass collects the count of all instructions and reports them.
181 ``-intervals``: Interval Partition Construction
182 -----------------------------------------------
184 This analysis calculates and represents the interval partition of a function,
185 or a preexisting interval partition.
187 In this way, the interval partition may be used to reduce a flow graph down to
188 its degenerate single node interval partition (unless it is irreducible).
190 ``-iv-users``: Induction Variable Users
191 ---------------------------------------
193 Bookkeeping for "interesting" users of expressions computed from induction
196 ``-lazy-value-info``: Lazy Value Information Analysis
197 -----------------------------------------------------
199 Interface for lazy computation of value constraint information.
201 ``-libcall-aa``: LibCall Alias Analysis
202 ---------------------------------------
204 LibCall Alias Analysis.
206 ``-lint``: Statically lint-checks LLVM IR
207 -----------------------------------------
209 This pass statically checks for common and easily-identified constructs which
210 produce undefined or likely unintended behavior in LLVM IR.
212 It is not a guarantee of correctness, in two ways. First, it isn't
213 comprehensive. There are checks which could be done statically which are not
214 yet implemented. Some of these are indicated by TODO comments, but those
215 aren't comprehensive either. Second, many conditions cannot be checked
216 statically. This pass does no dynamic instrumentation, so it can't check for
217 all possible problems.
219 Another limitation is that it assumes all code will be executed. A store
220 through a null pointer in a basic block which is never reached is harmless, but
221 this pass will warn about it anyway.
223 Optimization passes may make conditions that this pass checks for more or less
224 obvious. If an optimization pass appears to be introducing a warning, it may
225 be that the optimization pass is merely exposing an existing condition in the
228 This code may be run before :ref:`instcombine <passes-instcombine>`. In many
229 cases, instcombine checks for the same kinds of things and turns instructions
230 with undefined behavior into unreachable (or equivalent). Because of this,
231 this pass makes some effort to look through bitcasts and so on.
233 ``-loops``: Natural Loop Information
234 ------------------------------------
236 This analysis is used to identify natural loops and determine the loop depth of
237 various nodes of the CFG. Note that the loops identified may actually be
238 several natural loops that share the same header node... not just a single
241 ``-memdep``: Memory Dependence Analysis
242 ---------------------------------------
244 An analysis that determines, for a given memory operation, what preceding
245 memory operations it depends on. It builds on alias analysis information, and
246 tries to provide a lazy, caching interface to a common kind of alias
249 ``-module-debuginfo``: Decodes module-level debug info
250 ------------------------------------------------------
252 This pass decodes the debug info metadata in a module and prints in a
253 (sufficiently-prepared-) human-readable form.
255 For example, run this pass from ``opt`` along with the ``-analyze`` option, and
256 it'll print to standard output.
258 ``-postdomfrontier``: Post-Dominance Frontier Construction
259 ----------------------------------------------------------
261 This pass is a simple post-dominator construction algorithm for finding
262 post-dominator frontiers.
264 ``-postdomtree``: Post-Dominator Tree Construction
265 --------------------------------------------------
267 This pass is a simple post-dominator construction algorithm for finding
270 ``-print-alias-sets``: Alias Set Printer
271 ----------------------------------------
275 ``-print-callgraph``: Print a call graph
276 ----------------------------------------
278 This pass, only available in ``opt``, prints the call graph to standard error
279 in a human-readable form.
281 ``-print-callgraph-sccs``: Print SCCs of the Call Graph
282 -------------------------------------------------------
284 This pass, only available in ``opt``, prints the SCCs of the call graph to
285 standard error in a human-readable form.
287 ``-print-cfg-sccs``: Print SCCs of each function CFG
288 ----------------------------------------------------
290 This pass, only available in ``opt``, printsthe SCCs of each function CFG to
291 standard error in a human-readable fom.
293 ``-print-dom-info``: Dominator Info Printer
294 -------------------------------------------
296 Dominator Info Printer.
298 ``-print-externalfnconstants``: Print external fn callsites passed constants
299 ----------------------------------------------------------------------------
301 This pass, only available in ``opt``, prints out call sites to external
302 functions that are called with constant arguments. This can be useful when
303 looking for standard library functions we should constant fold or handle in
306 ``-print-function``: Print function to stderr
307 ---------------------------------------------
309 The ``PrintFunctionPass`` class is designed to be pipelined with other
310 ``FunctionPasses``, and prints out the functions of the module as they are
313 ``-print-module``: Print module to stderr
314 -----------------------------------------
316 This pass simply prints out the entire module when it is executed.
318 .. _passes-print-used-types:
320 ``-print-used-types``: Find Used Types
321 --------------------------------------
323 This pass is used to seek out all of the types in use by the program. Note
324 that this analysis explicitly does not include types only used by the symbol
327 ``-regions``: Detect single entry single exit regions
328 -----------------------------------------------------
330 The ``RegionInfo`` pass detects single entry single exit regions in a function,
331 where a region is defined as any subgraph that is connected to the remaining
332 graph at only two spots. Furthermore, an hierarchical region tree is built.
334 ``-scalar-evolution``: Scalar Evolution Analysis
335 ------------------------------------------------
337 The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar
338 expressions in loops. It specializes in recognizing general induction
339 variables, representing them with the abstract and opaque ``SCEV`` class.
340 Given this analysis, trip counts of loops and other important properties can be
343 This analysis is primarily useful for induction variable substitution and
346 ``-scev-aa``: ScalarEvolution-based Alias Analysis
347 --------------------------------------------------
349 Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
351 This differs from traditional loop dependence analysis in that it tests for
352 dependencies within a single iteration of a loop, rather than dependencies
353 between different iterations.
355 ``ScalarEvolution`` has a more complete understanding of pointer arithmetic
356 than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
358 ``-targetdata``: Target Data Layout
359 -----------------------------------
361 Provides other passes access to information on how the size and alignment
362 required by the target ABI for various data types.
367 This section describes the LLVM Transform Passes.
369 ``-adce``: Aggressive Dead Code Elimination
370 -------------------------------------------
372 ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE
373 <passes-dce>` but it assumes that values are dead until proven otherwise. This
374 is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
377 ``-always-inline``: Inliner for ``always_inline`` functions
378 -----------------------------------------------------------
380 A custom inliner that handles only functions that are marked as "always
383 ``-argpromotion``: Promote 'by reference' arguments to scalars
384 --------------------------------------------------------------
386 This pass promotes "by reference" arguments to be "by value" arguments. In
387 practice, this means looking for internal functions that have pointer
388 arguments. If it can prove, through the use of alias analysis, that an
389 argument is *only* loaded, then it can pass the value into the function instead
390 of the address of the value. This can cause recursive simplification of code
391 and lead to the elimination of allocas (especially in C++ template code like
394 This pass also handles aggregate arguments that are passed into a function,
395 scalarizing them if the elements of the aggregate are only loaded. Note that
396 it refuses to scalarize aggregates which would require passing in more than
397 three operands to the function, because passing thousands of operands for a
398 large array or structure is unprofitable!
400 Note that this transformation could also be done for arguments that are only
401 stored to (returning the value instead), but does not currently. This case
402 would be best handled when and if LLVM starts supporting multiple return values
405 ``-bb-vectorize``: Basic-Block Vectorization
406 --------------------------------------------
408 This pass combines instructions inside basic blocks to form vector
409 instructions. It iterates over each basic block, attempting to pair compatible
410 instructions, repeating this process until no additional pairs are selected for
411 vectorization. When the outputs of some pair of compatible instructions are
412 used as inputs by some other pair of compatible instructions, those pairs are
413 part of a potential vectorization chain. Instruction pairs are only fused into
414 vector instructions when they are part of a chain longer than some threshold
415 length. Moreover, the pass attempts to find the best possible chain for each
416 pair of compatible instructions. These heuristics are intended to prevent
417 vectorization in cases where it would not yield a performance increase of the
420 ``-block-placement``: Profile Guided Basic Block Placement
421 ----------------------------------------------------------
423 This pass is a very simple profile guided basic block placement algorithm. The
424 idea is to put frequently executed blocks together at the start of the function
425 and hopefully increase the number of fall-through conditional branches. If
426 there is no profile information for a particular function, this pass basically
427 orders blocks in depth-first order.
429 ``-break-crit-edges``: Break critical edges in CFG
430 --------------------------------------------------
432 Break all of the critical edges in the CFG by inserting a dummy basic block.
433 It may be "required" by passes that cannot deal with critical edges. This
434 transformation obviously invalidates the CFG, but can update forward dominator
435 (set, immediate dominators, tree, and frontier) information.
437 ``-codegenprepare``: Optimize for code generation
438 -------------------------------------------------
440 This pass munges the code in the input function to better prepare it for
441 SelectionDAG-based code generation. This works around limitations in its
442 basic-block-at-a-time approach. It should eventually be removed.
444 ``-constmerge``: Merge Duplicate Global Constants
445 -------------------------------------------------
447 Merges duplicate global constants together into a single constant that is
448 shared. This is useful because some passes (i.e., TraceValues) insert a lot of
449 string constants into the program, regardless of whether or not an existing
452 ``-constprop``: Simple constant propagation
453 -------------------------------------------
455 This pass implements constant propagation and merging. It looks for
456 instructions involving only constant operands and replaces them with a constant
457 value instead of an instruction. For example:
469 NOTE: this pass has a habit of making definitions be dead. It is a good idea
470 to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime after
475 ``-dce``: Dead Code Elimination
476 -------------------------------
478 Dead code elimination is similar to :ref:`dead instruction elimination
479 <passes-die>`, but it rechecks instructions that were used by removed
480 instructions to see if they are newly dead.
482 ``-deadargelim``: Dead Argument Elimination
483 -------------------------------------------
485 This pass deletes dead arguments from internal functions. Dead argument
486 elimination removes arguments which are directly dead, as well as arguments
487 only passed into function calls as dead arguments of other functions. This
488 pass also deletes dead arguments in a similar way.
490 This pass is often useful as a cleanup pass to run after aggressive
491 interprocedural passes, which add possibly-dead arguments.
493 ``-deadtypeelim``: Dead Type Elimination
494 ----------------------------------------
496 This pass is used to cleanup the output of GCC. It eliminate names for types
497 that are unused in the entire translation unit, using the :ref:`find used types
498 <passes-print-used-types>` pass.
502 ``-die``: Dead Instruction Elimination
503 --------------------------------------
505 Dead instruction elimination performs a single pass over the function, removing
506 instructions that are obviously dead.
508 ``-dse``: Dead Store Elimination
509 --------------------------------
511 A trivial dead store elimination that only considers basic-block local
514 .. _passes-functionattrs:
516 ``-functionattrs``: Deduce function attributes
517 ----------------------------------------------
519 A simple interprocedural pass which walks the call-graph, looking for functions
520 which do not access or only read non-local memory, and marking them
521 ``readnone``/``readonly``. In addition, it marks function arguments (of
522 pointer type) "``nocapture``" if a call to the function does not create any
523 copies of the pointer value that outlive the call. This more or less means
524 that the pointer is only dereferenced, and not returned from the function or
525 stored in a global. This pass is implemented as a bottom-up traversal of the
528 ``-globaldce``: Dead Global Elimination
529 ---------------------------------------
531 This transform is designed to eliminate unreachable internal globals from the
532 program. It uses an aggressive algorithm, searching out globals that are known
533 to be alive. After it finds all of the globals which are needed, it deletes
534 whatever is left over. This allows it to delete recursive chunks of the
535 program which are unreachable.
537 ``-globalopt``: Global Variable Optimizer
538 -----------------------------------------
540 This pass transforms simple global variables that never have their address
541 taken. If obviously true, it marks read/write globals as constant, deletes
542 variables only stored to, etc.
544 ``-gvn``: Global Value Numbering
545 --------------------------------
547 This pass performs global value numbering to eliminate fully and partially
548 redundant instructions. It also performs redundant load elimination.
552 ``-indvars``: Canonicalize Induction Variables
553 ----------------------------------------------
555 This transformation analyzes and transforms the induction variables (and
556 computations derived from them) into simpler forms suitable for subsequent
557 analysis and transformation.
559 This transformation makes the following changes to each loop with an
560 identifiable induction variable:
562 * All loops are transformed to have a *single* canonical induction variable
563 which starts at zero and steps by one.
564 * The canonical induction variable is guaranteed to be the first PHI node in
565 the loop header block.
566 * Any pointer arithmetic recurrences are raised to use array subscripts.
568 If the trip count of a loop is computable, this pass also makes the following
571 * The exit condition for the loop is canonicalized to compare the induction
572 value against the exit value. This turns loops like:
576 for (i = 7; i*i < 1000; ++i)
582 for (i = 0; i != 25; ++i)
584 * Any use outside of the loop of an expression derived from the indvar is
585 changed to compute the derived value outside of the loop, eliminating the
586 dependence on the exit value of the induction variable. If the only purpose
587 of the loop is to compute the exit value of some derived expression, this
588 transformation will make the loop dead.
590 This transformation should be followed by strength reduction after all of the
591 desired loop transformations have been performed. Additionally, on targets
592 where it is profitable, the loop could be transformed to count down to zero
593 (the "do loop" optimization).
595 ``-inline``: Function Integration/Inlining
596 ------------------------------------------
598 Bottom-up inlining of functions into callees.
600 .. _passes-instcombine:
602 ``-instcombine``: Combine redundant instructions
603 ------------------------------------------------
605 Combine instructions to form fewer, simple instructions. This pass does not
606 modify the CFG. This pass is where algebraic simplification happens.
608 This pass combines things like:
621 This is a simple worklist driven algorithm.
623 This pass guarantees that the following canonicalizations are performed on the
626 #. If a binary operator has a constant operand, it is moved to the right-hand
628 #. Bitwise operators with constant operands are always grouped so that shifts
629 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
630 #. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
631 ``=`` or ``≠`` if possible.
632 #. All ``cmp`` instructions on boolean values are replaced with logical
634 #. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
635 #. Multiplies with a constant power-of-two argument are transformed into
639 This pass can also simplify calls to specific well-known function calls (e.g.
640 runtime library functions). For example, a call ``exit(3)`` that occurs within
641 the ``main()`` function can be transformed into simply ``return 3``. Whether or
642 not library calls are simplified is controlled by the
643 :ref:`-functionattrs <passes-functionattrs>` pass and LLVM's knowledge of
644 library calls on different targets.
646 .. _passes-aggressive-instcombine:
648 ``-aggressive-instcombine``: Combine expression patterns
649 --------------------------------------------------------
651 Combine expression patterns to form expressions with fewer, simple instructions.
652 This pass does not modify the CFG.
654 For example, this pass reduce width of expressions post-dominated by TruncInst
655 into smaller width when applicable.
657 It differs from instcombine pass in that it contains pattern optimization that
658 requires higher complexity than the O(1), thus, it should run fewer times than
661 ``-internalize``: Internalize Global Symbols
662 --------------------------------------------
664 This pass loops over all of the functions in the input module, looking for a
665 main function. If a main function is found, all other functions and all global
666 variables with initializers are marked as internal.
668 ``-ipconstprop``: Interprocedural constant propagation
669 ------------------------------------------------------
671 This pass implements an *extremely* simple interprocedural constant propagation
672 pass. It could certainly be improved in many different ways, like using a
673 worklist. This pass makes arguments dead, but does not remove them. The
674 existing dead argument elimination pass should be run after this to clean up
677 ``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation
678 --------------------------------------------------------------------
680 An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
683 ``-jump-threading``: Jump Threading
684 -----------------------------------
686 Jump threading tries to find distinct threads of control flow running through a
687 basic block. This pass looks at blocks that have multiple predecessors and
688 multiple successors. If one or more of the predecessors of the block can be
689 proven to always cause a jump to one of the successors, we forward the edge
690 from the predecessor to the successor by duplicating the contents of this
693 An example of when this can occur is code like this:
702 In this case, the unconditional branch at the end of the first if can be
703 revectored to the false side of the second if.
705 ``-lcssa``: Loop-Closed SSA Form Pass
706 -------------------------------------
708 This pass transforms loops by placing phi nodes at the end of the loops for all
709 values that are live across the loop boundary. For example, it turns the left
719 X3 = phi(X1, X2) X3 = phi(X1, X2)
720 ... = X3 + 4 X4 = phi(X3)
723 This is still valid LLVM; the extra phi nodes are purely redundant, and will be
724 trivially eliminated by ``InstCombine``. The major benefit of this
725 transformation is that it makes many other loop optimizations, such as
726 ``LoopUnswitch``\ ing, simpler.
730 ``-licm``: Loop Invariant Code Motion
731 -------------------------------------
733 This pass performs loop invariant code motion, attempting to remove as much
734 code from the body of a loop as possible. It does this by either hoisting code
735 into the preheader block, or by sinking code to the exit blocks if it is safe.
736 This pass also promotes must-aliased memory locations in the loop to live in
737 registers, thus hoisting and sinking "invariant" loads and stores.
739 This pass uses alias analysis for two purposes:
741 #. Moving loop invariant loads and calls out of loops. If we can determine
742 that a load or call inside of a loop never aliases anything stored to, we
743 can hoist it or sink it like any other instruction.
745 #. Scalar Promotion of Memory. If there is a store instruction inside of the
746 loop, we try to move the store to happen AFTER the loop instead of inside of
747 the loop. This can only happen if a few conditions are true:
749 #. The pointer stored through is loop invariant.
750 #. There are no stores or loads in the loop which *may* alias the pointer.
751 There are no calls in the loop which mod/ref the pointer.
753 If these conditions are true, we can promote the loads and stores in the
754 loop of the pointer to use a temporary alloca'd variable. We then use the
755 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
756 SSA form for the variable.
758 ``-loop-deletion``: Delete dead loops
759 -------------------------------------
761 This file implements the Dead Loop Deletion Pass. This pass is responsible for
762 eliminating loops with non-infinite computable trip counts that have no side
763 effects or volatile instructions, and do not contribute to the computation of
764 the function's return value.
766 .. _passes-loop-extract:
768 ``-loop-extract``: Extract loops into new functions
769 ---------------------------------------------------
771 A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
772 each top-level loop into its own new function. If the loop is the *only* loop
773 in a given function, it is not touched. This is a pass most useful for
774 debugging via bugpoint.
776 ``-loop-extract-single``: Extract at most one loop into a new function
777 ----------------------------------------------------------------------
779 Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this
780 pass extracts one natural loop from the program into a function if it can.
781 This is used by :program:`bugpoint`.
783 ``-loop-reduce``: Loop Strength Reduction
784 -----------------------------------------
786 This pass performs a strength reduction on array references inside loops that
787 have as one or more of their components the loop induction variable. This is
788 accomplished by creating a new value to hold the initial value of the array
789 access for the first iteration, and then creating a new GEP instruction in the
790 loop to increment the value by the appropriate amount.
792 ``-loop-rotate``: Rotate Loops
793 ------------------------------
795 A simple loop rotation transformation.
797 ``-loop-simplify``: Canonicalize natural loops
798 ----------------------------------------------
800 This pass performs several transformations to transform natural loops into a
801 simpler form, which makes subsequent analyses and transformations simpler and
804 Loop pre-header insertion guarantees that there is a single, non-critical entry
805 edge from outside of the loop to the loop header. This simplifies a number of
806 analyses and transformations, such as :ref:`LICM <passes-licm>`.
808 Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
809 which are outside of the loop that have predecessors inside of the loop) only
810 have predecessors from inside of the loop (and are thus dominated by the loop
811 header). This simplifies transformations such as store-sinking that are built
814 This pass also guarantees that loops will have exactly one backedge.
816 Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
817 which are split out but end up being unnecessary, so usage of this pass should
818 not pessimize generated code.
820 This pass obviously modifies the CFG, but updates loop information and
821 dominator information.
823 ``-loop-unroll``: Unroll loops
824 ------------------------------
826 This pass implements a simple loop unroller. It works best when loops have
827 been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
828 determine the trip counts of loops easily.
830 ``-loop-unroll-and-jam``: Unroll and Jam loops
831 ----------------------------------------------
833 This pass implements a simple unroll and jam classical loop optimisation pass.
834 It transforms loop from:
838 for i.. i+= 1 for i.. i+= 4
840 code(i, j) code(i, j)
846 Which can be seen as unrolling the outer loop and "jamming" (fusing) the inner
847 loops into one. When variables or loads can be shared in the new inner loop, this
848 can lead to significant performance improvements. It uses
849 :ref:`Dependence Analysis <passes-da>` for proving the transformations are safe.
851 ``-loop-unswitch``: Unswitch loops
852 ----------------------------------
854 This pass transforms loops that contain branches on loop-invariant conditions
855 to have multiple loops. For example, it turns the left into the right code:
866 This can increase the size of the code exponentially (doubling it every time a
867 loop is unswitched) so we only unswitch if the resultant code will be smaller
870 This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
871 invariant conditions out of the loop, to make the unswitching opportunity
874 ``-loweratomic``: Lower atomic intrinsics to non-atomic form
875 ------------------------------------------------------------
877 This pass lowers atomic intrinsics to non-atomic form for use in a known
878 non-preemptible environment.
880 The pass does not verify that the environment is non-preemptible (in general
881 this would require knowledge of the entire call graph of the program including
882 any libraries which may not be available in bitcode form); it simply lowers
883 every atomic intrinsic.
885 ``-lowerinvoke``: Lower invokes to calls, for unwindless code generators
886 ------------------------------------------------------------------------
888 This transformation is designed for use by code generators which do not yet
889 support stack unwinding. This pass converts ``invoke`` instructions to
890 ``call`` instructions, so that any exception-handling ``landingpad`` blocks
891 become dead code (which can be removed by running the ``-simplifycfg`` pass
894 ``-lowerswitch``: Lower ``SwitchInst``\ s to branches
895 -----------------------------------------------------
897 Rewrites switch instructions with a sequence of branches, which allows targets
898 to get away with not implementing the switch instruction until it is
903 ``-mem2reg``: Promote Memory to Register
904 ----------------------------------------
906 This file promotes memory references to be register references. It promotes
907 alloca instructions which only have loads and stores as uses. An ``alloca`` is
908 transformed by using dominator frontiers to place phi nodes, then traversing
909 the function in depth-first order to rewrite loads and stores as appropriate.
910 This is just the standard SSA construction algorithm to construct "pruned" SSA
913 ``-memcpyopt``: MemCpy Optimization
914 -----------------------------------
916 This pass performs various transformations related to eliminating ``memcpy``
917 calls, or transforming sets of stores into ``memset``\ s.
919 ``-mergefunc``: Merge Functions
920 -------------------------------
922 This pass looks for equivalent functions that are mergable and folds them.
924 Total-ordering is introduced among the functions set: we define comparison
925 that answers for every two functions which of them is greater. It allows to
926 arrange functions into the binary tree.
928 For every new function we check for equivalent in tree.
930 If equivalent exists we fold such functions. If both functions are overridable,
931 we move the functionality into a new internal function and leave two
932 overridable thunks to it.
934 If there is no equivalent, then we add this function to tree.
936 Lookup routine has O(log(n)) complexity, while whole merging process has
937 complexity of O(n*log(n)).
940 :doc:`this <MergeFunctions>`
941 article for more details.
943 ``-mergereturn``: Unify function exit nodes
944 -------------------------------------------
946 Ensure that functions have at most one ``ret`` instruction in them.
947 Additionally, it keeps track of which node is the new exit node of the CFG.
949 ``-partial-inliner``: Partial Inliner
950 -------------------------------------
952 This pass performs partial inlining, typically by inlining an ``if`` statement
953 that surrounds the body of the function.
955 ``-prune-eh``: Remove unused exception handling info
956 ----------------------------------------------------
958 This file implements a simple interprocedural pass which walks the call-graph,
959 turning invoke instructions into call instructions if and only if the callee
960 cannot throw an exception. It implements this as a bottom-up traversal of the
963 ``-reassociate``: Reassociate expressions
964 -----------------------------------------
966 This pass reassociates commutative expressions in an order that is designed to
967 promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
969 For example: 4 + (x + 5) ⇒ x + (4 + 5)
971 In the implementation of this algorithm, constants are assigned rank = 0,
972 function arguments are rank = 1, and other values are assigned ranks
973 corresponding to the reverse post order traversal of current function (starting
974 at 2), which effectively gives values in deep loops higher rank than values not
977 ``-reg2mem``: Demote all values to stack slots
978 ----------------------------------------------
980 This file demotes all registers to memory references. It is intended to be the
981 inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``
982 instructions, the only values live across basic blocks are ``alloca``
983 instructions and ``load`` instructions before ``phi`` nodes. It is intended
984 that this should make CFG hacking much easier. To make later hacking easier,
985 the entry block is split into two, such that all introduced ``alloca``
986 instructions (and nothing else) are in the entry block.
988 ``-sroa``: Scalar Replacement of Aggregates
989 ------------------------------------------------------
991 The well-known scalar replacement of aggregates transformation. This transform
992 breaks up ``alloca`` instructions of aggregate type (structure or array) into
993 individual ``alloca`` instructions for each member if possible. Then, if
994 possible, it transforms the individual ``alloca`` instructions into nice clean
999 ``-sccp``: Sparse Conditional Constant Propagation
1000 --------------------------------------------------
1002 Sparse conditional constant propagation and merging, which can be summarized
1005 * Assumes values are constant unless proven otherwise
1006 * Assumes BasicBlocks are dead unless proven otherwise
1007 * Proves values to be constant, and replaces them with constants
1008 * Proves conditional branches to be unconditional
1010 Note that this pass has a habit of making definitions be dead. It is a good
1011 idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
1013 .. _passes-simplifycfg:
1015 ``-simplifycfg``: Simplify the CFG
1016 ----------------------------------
1018 Performs dead code elimination and basic block merging. Specifically:
1020 * Removes basic blocks with no predecessors.
1021 * Merges a basic block into its predecessor if there is only one and the
1022 predecessor only has one successor.
1023 * Eliminates PHI nodes for basic blocks with a single predecessor.
1024 * Eliminates a basic block that only contains an unconditional branch.
1026 ``-sink``: Code sinking
1027 -----------------------
1029 This pass moves instructions into successor blocks, when possible, so that they
1030 aren't executed on paths where their results aren't needed.
1032 ``-strip``: Strip all symbols from a module
1033 -------------------------------------------
1035 Performs code stripping. This transformation can delete:
1037 * names for virtual registers
1038 * symbols for internal globals and functions
1041 Note that this transformation makes code much less readable, so it should only
1042 be used in situations where the strip utility would be used, such as reducing
1043 code size or making it harder to reverse engineer code.
1045 ``-strip-dead-debug-info``: Strip debug info for unused symbols
1046 ---------------------------------------------------------------
1048 .. FIXME: this description is the same as for -strip
1050 performs code stripping. this transformation can delete:
1052 * names for virtual registers
1053 * symbols for internal globals and functions
1056 note that this transformation makes code much less readable, so it should only
1057 be used in situations where the strip utility would be used, such as reducing
1058 code size or making it harder to reverse engineer code.
1060 ``-strip-dead-prototypes``: Strip Unused Function Prototypes
1061 ------------------------------------------------------------
1063 This pass loops over all of the functions in the input module, looking for dead
1064 declarations and removes them. Dead declarations are declarations of functions
1065 for which no implementation is available (i.e., declarations for unused library
1068 ``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics
1069 -------------------------------------------------------------------
1071 .. FIXME: this description is the same as for -strip
1073 This pass implements code stripping. Specifically, it can delete:
1075 #. names for virtual registers
1076 #. symbols for internal globals and functions
1077 #. debug information
1079 Note that this transformation makes code much less readable, so it should only
1080 be used in situations where the 'strip' utility would be used, such as reducing
1081 code size or making it harder to reverse engineer code.
1083 ``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module
1084 -------------------------------------------------------------------------
1086 .. FIXME: this description is the same as for -strip
1088 This pass implements code stripping. Specifically, it can delete:
1090 #. names for virtual registers
1091 #. symbols for internal globals and functions
1092 #. debug information
1094 Note that this transformation makes code much less readable, so it should only
1095 be used in situations where the 'strip' utility would be used, such as reducing
1096 code size or making it harder to reverse engineer code.
1098 ``-tailcallelim``: Tail Call Elimination
1099 ----------------------------------------
1101 This file transforms calls of the current function (self recursion) followed by
1102 a return instruction with a branch to the entry of the function, creating a
1103 loop. This pass also implements the following extensions to the basic
1106 #. Trivial instructions between the call and return do not prevent the
1107 transformation from taking place, though currently the analysis cannot
1108 support moving any really useful instructions (only dead ones).
1109 #. This pass transforms functions that are prevented from being tail recursive
1110 by an associative expression to use an accumulator variable, thus compiling
1111 the typical naive factorial or fib implementation into efficient code.
1112 #. TRE is performed if the function returns void, if the return returns the
1113 result returned by the call, or if the function returns a run-time constant
1114 on all exits from the function. It is possible, though unlikely, that the
1115 return returns something else (like constant 0), and can still be TRE'd. It
1116 can be TRE'd if *all other* return instructions in the function return the
1118 #. If it can prove that callees do not access theier caller stack frame, they
1119 are marked as eligible for tail call elimination (by the code generator).
1124 This section describes the LLVM Utility Passes.
1126 ``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
1127 ------------------------------------------------------------------------
1129 Same as dead argument elimination, but deletes arguments to functions which are
1130 external. This is only for use by :doc:`bugpoint <Bugpoint>`.
1132 ``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
1133 ------------------------------------------------------------------------
1135 This pass is used by bugpoint to extract all blocks from the module into their
1138 ``-instnamer``: Assign names to anonymous instructions
1139 ------------------------------------------------------
1141 This is a little utility pass that gives instructions names, this is mostly
1142 useful when diffing the effect of an optimization because deleting an unnamed
1143 instruction can change all other instruction numbering, making the diff very
1148 ``-verify``: Module Verifier
1149 ----------------------------
1151 Verifies an LLVM IR code. This is useful to run after an optimization which is
1152 undergoing testing. Note that llvm-as verifies its input before emitting
1153 bitcode, and also that malformed bitcode is likely to make LLVM crash. All
1154 language front-ends are therefore encouraged to verify their output before
1155 performing optimizing transformations.
1157 #. Both of a binary operator's parameters are of the same type.
1158 #. Verify that the indices of mem access instructions match other operands.
1159 #. Verify that arithmetic and other things are only performed on first-class
1160 types. Verify that shifts and logicals only happen on integrals f.e.
1161 #. All of the constants in a switch statement are of the correct type.
1162 #. The code is in valid SSA form.
1163 #. It is illegal to put a label into any other type (like a structure) or to
1165 #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
1167 #. PHI nodes must have an entry for each predecessor, with no extras.
1168 #. PHI nodes must be the first thing in a basic block, all grouped together.
1169 #. PHI nodes must have at least one entry.
1170 #. All basic blocks should only end with terminator insts, not contain them.
1171 #. The entry node to a function must not have predecessors.
1172 #. All Instructions must be embedded into a basic block.
1173 #. Functions cannot take a void-typed parameter.
1174 #. Verify that a function's argument list agrees with its declared type.
1175 #. It is illegal to specify a name for a void value.
1176 #. It is illegal to have an internal global value with no initializer.
1177 #. It is illegal to have a ``ret`` instruction that returns a value that does
1178 not agree with the function return value type.
1179 #. Function call argument types match the function prototype.
1180 #. All other things that are tested by asserts spread about the code.
1182 Note that this does not provide full security verification (like Java), but
1183 instead just tries to ensure that code is well-formed.
1185 ``-view-cfg``: View CFG of function
1186 -----------------------------------
1188 Displays the control flow graph using the GraphViz tool.
1190 ``-view-cfg-only``: View CFG of function (with no function bodies)
1191 ------------------------------------------------------------------
1193 Displays the control flow graph using the GraphViz tool, but omitting function
1196 ``-view-dom``: View dominance tree of function
1197 ----------------------------------------------
1199 Displays the dominator tree using the GraphViz tool.
1201 ``-view-dom-only``: View dominance tree of function (with no function bodies)
1202 -----------------------------------------------------------------------------
1204 Displays the dominator tree using the GraphViz tool, but omitting function
1207 ``-view-postdom``: View postdominance tree of function
1208 ------------------------------------------------------
1210 Displays the post dominator tree using the GraphViz tool.
1212 ``-view-postdom-only``: View postdominance tree of function (with no function bodies)
1213 -------------------------------------------------------------------------------------
1215 Displays the post dominator tree using the GraphViz tool, but omitting function